动手学深度学习——文本预处理

文本预处理

文本预处理是NLP中不可或缺的一项任务。文本预处理通常包括四个步骤:读入文本、分词、建立字典、将文本从词序列转换为索引序列。

(1)读入文本
import collections
import re

def read_time_machine():
    with open('/home/kesci/input/timemachine7163/timemachine.txt', 'r') as f:  #以读的方式打开文本,并重新命名为f
        lines = [re.sub('[^a-z]+', ' ', line.strip().lower()) for line in f]  #将不是字母的替换为空格,去掉每行的空格并将所有的字母小写
    return lines
    
lines = read_time_machine()
print('# sentences %d' % len(lines))
(2)分词
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)

tokens = tokenize(lines)
tokens[0:2]
(3)建立字典
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 = []
        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]])

另外,对于如“shouldn’t", “doesn’t”,“Mr.”, "Dr."等词上述分词方法不适用,会被错误处理,可用spaCy和NLTK两个工具进行处理。

注:上述资料来源于伯禹平台的《动手学深度学习》的 学习笔记。

发布了19 篇原创文章 · 获赞 17 · 访问量 1465

猜你喜欢

转载自blog.csdn.net/weixin_43839651/article/details/104317538
今日推荐