文本预处理
文本是一类序列数据,一篇文章可以看作是字符或单词的序列。用神经网络处理文本时会存在一个问题,文本实际上是字符串,但神经网络是做数值处理,无法直接作用于字符串,因此,我们需要对文本进行预处理。
接下来介绍一些基础的步骤。
读入文本
用H.G.Well的Time Machine作为示例。
import collections
import re
def read_time_machine():
with open('<your-path>/timemachine.txt','r') as f:
# 这条语句就是将文本每一行全部转化为小写
# 且将非小写字母的其他字符全部用空格代替
lines = [re.sub('[^a-z]+','',line.strip().lower()) for line in f:]
return lines
lines = read_time_machine() # type is list
print('# sentences %d' % len(lines))
output:
# sentences 3221
- collections模块:数据结构常用模块,常用类型有:计数器(Counter)、双向队列(deque)、默认字典(defaultdict)、有序字典(OrderedDict)、可命名元组(namedtuple)。Counter对访问对象进行计数并返回一个字典,具体可参考OneMore
- re模块:python独有的匹配字符串的模块,多基于正则表达式实现,具体可参考Brigth-Python之re模块
- open(file, mode=‘r’, buffering=-1, encoding=None, errors=None, newline=None, closefd=True, opener=None)函数用于打开文件并进行相应处理,可用的模式有很多,这里介绍几个常见的:
‘r’——以只读方式打开文件。文件的指针将会放在文件的开头。这是默认模式。
’r+‘——打开一个文件用于读写。文件指针将会放在文件的开头。
’w‘——打开一个文件只用于写入。如果该文件已存在则打开文件,并从开头开始编辑,即原有内容会被删除。如果该文件不存在,创建新文件。
‘w+’——打开一个文件用于读写。如果该文件已存在则打开文件,并从开头开始编辑,即原有内容会被删除。如果该文件不存在,创建新文件。 - re.sub(pattern,repl,string,count = 0,flags = 0 ):pattern是字符的模式,repl用于替换字符串中对应pattern的对象,它可以时函数,也可以是字符串,string即要替换的字符串序列,count表示替换的次数。
import re
# 将查找到的数字替换成AA,替换2次
x = re.sub('\d', 'AA', 'fhd638dnhs687f', 2)
# 默认全部替换
y = re.sub('\d', 'AA', 'fhd638dnhs687f')
print(x)
print(y)
output:
'fhdAAAA8dnhs687f'
'fhdAAAAAAdnhsAAAAAAf'
- [a-z]——表示从a到z所有小写字母的字符组,[^…]——表示除了字符组中字符的所有其他字符,+——表示重复一次或多次。因此[^a-z]+表示除了所有小写字母以外的字符,这些其他字符重复一次或多次全都计算在内。
- strip()方法:str.strip()用于移除字符串头尾指定的字符(默认为空格或换行符)或字符序列。注意:该方法只能删除开头或是结尾的字符,不能删除中间部分的字符。
- lower() 方法:str.lower()转换字符串中所有大写字符为小写。
分词
我们对每个句子进行分词,也就是将一个句子划分成若干个词(token),转换为一个词的序列。
def tokenize(sentences, token='word'):
"""Split sentences into word or char tokens"""
# 做单词级别的分词
if token == 'word':
return [sentence.split(' ') for sentence in sentences]
# 做字符级别的分词
elif token == 'char':
return [list(sentence) for sentence in sentences]
else:
print('ERROR: unkown token type '+token)
# 返回一个二维列表,第一个维度是sentences中每个句子,
# 第二个维度是每个句子分词之后得到的单词或序列
tokens = tokenize(lines)
tokens[0:2]
output:
[['the', 'time', 'machine', 'by', 'h', 'g', 'wells', ''], ['']]
建立字典
为了方便模型处理,我们需要将字符串转换为数字。因此我们需要先构建一个字典(vocabulary),将每个词映射到一个唯一的索引编号。
class Vocab(object):
def __init__(self, tokens, min_freq=0, use_special_tokens=False):
'''
tokens是一个二维列表,包含所有语句的词
min_freq设定一个词出现的最低频数,小于这个频数的词就忽略
use_special_tokens是否使用特殊的词
'''
# 进行去重与统计词频
counter = count_corpus(tokens) #
self.token_freqs = list(counter.items())
# print(self.token_freqs[0:2])
# output: [('the', 2261), ('time', 200)]
self.idx_to_token = []
if use_special_tokens:
# padding, begin of sentence, end of sentence, unknown
# self.pad:神经网络批量处理句子时以矩阵方式输入,每一行为一个句子,句子长短不一,因此padding
# self.bos:在句子首尾加上特殊字符,表明句子的开始和结束
# self.unk:语料库中没有出现过的词
self.pad, self.bos, self.eos, self.unk = (0, 1, 2, 3)
self.idx_to_token += ['', '', '', '']
else:
self.unk = 0
self.idx_to_token += ['']
self.idx_to_token += [token for token, freq in self.token_freqs
if freq >= min_freq and token not in self.idx_to_token]
# ind_to_token是包含了所有词的列表
# token_to_inx是一个字典:{'字符':下标}
self.token_to_idx = dict()
for idx, token in enumerate(self.idx_to_token):
self.token_to_idx[token] = idx
def __len__(self):
return len(self.idx_to_token)
def __getitem__(self, tokens):
if not isinstance(tokens, (list, tuple)):
return self.token_to_idx.get(tokens, self.unk)
return [self.__getitem__(token) for token in tokens]
# 根据下标返回token
def to_tokens(self, indices):
if not isinstance(indices, (list, tuple)):
return self.idx_to_token[indices]
return [self.idx_to_token[index] for index in indices]
def count_corpus(sentences):
tokens = [tk for st in sentences for tk in st]
return collections.Counter(tokens) # 返回一个字典,记录每个词的出现次数
vocab = Vocab(tokens)
print(list(vocab.token_to_idx.items())[0:10])
print(vocab.to_tokens([18,20]))
output:
[('', 0), ('the', 1), ('time', 2), ('machine', 3), ('by', 4), ('h', 5), ('g', 6), ('wells', 7), ('i', 8), ('traveller', 9)]
['of', 'was']
将词转化为索引
for i in range(8, 10):
print('words:', tokens[i])
print('indices:', vocab[tokens[i]])
output:
words: ['the', 'time', 'traveller', 'for', 'so', 'it', 'will', 'be', 'convenient', 'to', 'speak', 'of', 'him', '']
indices: [1, 2, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 0]
words: ['was', 'expounding', 'a', 'recondite', 'matter', 'to', 'us', 'his', 'grey', 'eyes', 'shone', 'and']
indices: [20, 21, 22, 23, 24, 16, 25, 26, 27, 28, 29, 30]
现有工具进行分词
上述分词方法简单且存在缺陷:
- 标点符号通常可以提供语义信息,但是我们的方法直接将其丢弃了
- 类似“shouldn’t", "doesn’t"这样的词会被错误地处理
- 类似"Mr.", "Dr."这样的词会被错误地处理
处理文本分词的工具包:是spaCy和NLTK
例子:
sapCy:
import spacy
text = "Mr. Chen doesn't agree with my suggestion."
nlp = spacy.load('en_core_web_sm')
doc = nlp(text)
print([token.text for token in doc])
output:
['Mr.', 'Chen', 'does', "n't", 'agree', 'with', 'my', 'suggestion', '.']
NLTK:
from nltk.tokenize import word_tokenize
from nltk import data
text = "Mr. Chen doesn't agree with my suggestion."
data.path.append('/home/kesci/input/nltk_data3784/nltk_data')
print(word_tokenize(text))
output:
['Mr.', 'Chen', 'does', "n't", 'agree', 'with', 'my', 'suggestion', '.']