文本预处理(pytorth实现):
1.读入文本
import re
def read_time_machine():
with open('/home/kesci/input/timemachine7163/timemachine.txt', 'r') as f:
lines = [re.sub('[^a-z]+', ' ', line.strip().lower()) for line in f]
# strip去掉了句头,句尾的空格。low将大写变为小写
#re.sub 正则表达式:非英文字符构成空格
return lines
lines = read_time_machine()
print('# sentences %d' % len(lines))
2.分词
不采取传统的分词方法,因为会丢语意信息,因此直接使用现有的工具进行很好的分词。比如
spaCy和 NLTK:
import spacy
nlp = spacy.load('en_core_web_sm')
doc = nlp(text)
print([token.text for token in doc])
from nltk.tokenize import word_tokenize
from nltk import data
data.path.append('/home/kesci/input/nltk_data3784/nltk_data')
print(word_tokenize(text))
3.建立字典
为了方便模型处理,我们需要将字符串转换为数字。因此我们需要先构建一个字典(vocabulary),将每个词映射到一个唯一的索引编号。
class Vocab(object):
#定义有一个类,提供词的索引编号。
def __init__(self, tokens, min_freq=0, use_special_tokens=False):
counter = count_corpus(tokens) # :去重, 统计词频
self.token_freqs = list(counter.items())
self.idx_to_token = []#控制列表,记录需要维护的token
if use_special_tokens:
# padding, begin of sentence, end of sentence, unknown
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]
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]
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) # 返回一个字典,记录每个词的出现次数
4.将词转换为索引
for i in range(8, 10):
print('words:', tokens[i])
print('indices:', vocab[tokens[i]])