文本預(yù)處理(pytorth實(shí)現(xiàn)):
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將大寫(xiě)變?yōu)樾?xiě)
#re.sub 正則表達(dá)式:非英文字符構(gòu)成空格
return lines
lines = read_time_machine()
print('# sentences %d' % len(lines))
2.分詞
?不采取傳統(tǒng)的分詞方法屿聋,因?yàn)闀?huì)丟語(yǔ)意信息,因此直接使用現(xiàn)有的工具進(jìn)行很好的分詞浅缸。比如
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.建立字典
? 為了方便模型處理,我們需要將字符串轉(zhuǎn)換為數(shù)字魄咕。因此我們需要先構(gòu)建一個(gè)字典(vocabulary)衩椒,將每個(gè)詞映射到一個(gè)唯一的索引編號(hào)。
class Vocab(object):
#定義有一個(gè)類哮兰,提供詞的索引編號(hào)毛萌。
def __init__(self, tokens, min_freq=0, use_special_tokens=False):
counter = count_corpus(tokens) # :去重, 統(tǒng)計(jì)詞頻
self.token_freqs = list(counter.items())
self.idx_to_token = []#控制列表喝滞,記錄需要維護(hù)的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) # 返回一個(gè)字典阁将,記錄每個(gè)詞的出現(xiàn)次數(shù)
4.將詞轉(zhuǎn)換為索引
for i in range(8, 10):
print('words:', tokens[i])
print('indices:', vocab[tokens[i]])