文本预处理

timemachine.txt数据下载地址

链接:https://pan.baidu.com/s/1RO2OLyTRQZ90HJUW7V7BCQ

提取码:bjox

NLTK数据集下载

链接:https://pan.baidu.com/s/1IvRhPOU2hUsQejQVunt5mQ

提取码:z2eh

文本是一类序列数据,一篇文章可以看作是字符或单词的序列,本节将介绍文本数据的常见预处理步骤,预处理通常包括四个步骤:

  1. 读入文本
  2. 分词
  3. 建立字典,将每个词映射到一个唯一的索引(index)
  4. 将文本从词的序列转换为索引的序列,方便输入模型

读入文本

我们用一部英文小说,即H. G. Well的Time Machine,作为示例,展示文本预处理的具体过程。

import collections
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]
return lines lines = read_time_machine()
print('# sentences %d' % len(lines))
# sentences 3221

分词

我们对每个句子进行分词,也就是将一个句子划分成若干个词(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) tokens = tokenize(lines)
tokens[0:2]
[['the', 'time', 'machine', 'by', 'h', 'g', 'wells', ''], ['']]

建立字典

为了方便模型处理,我们需要将字符串转换为数字。因此我们需要先构建一个字典(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 = []
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) # 返回一个字典,记录每个词的出现次数

我们看一个例子,这里我们尝试用Time Machine作为语料构建字典

vocab = Vocab(tokens)
print(list(vocab.token_to_idx.items())[0:10])
[('', 0), ('the', 1), ('time', 2), ('machine', 3), ('by', 4), ('h', 5), ('g', 6), ('wells', 7), ('i', 8), ('traveller', 9)]

将词转为索引

使用字典,我们可以将原文本中的句子从单词序列转换为索引序列

for i in range(8, 10):
print('words:', tokens[i])
print('indices:', vocab[tokens[i]])
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]

用现有工具进行分词

我们前面介绍的分词方式非常简单,它至少有以下几个缺点:

  1. 标点符号通常可以提供语义信息,但是我们的方法直接将其丢弃了
  2. 类似“shouldn’t", "doesn’t"这样的词会被错误地处理
  3. 类似"Mr.", "Dr."这样的词会被错误地处理

我们可以通过引入更复杂的规则来解决这些问题,但是事实上,有一些现有的工具可以很好地进行分词,我们在这里简单介绍其中的两个:spaCyNLTK

下面是一个简单的例子:

text = "Mr. Chen doesn't agree with my suggestion."

spaCy:

import spacy
nlp = spacy.load('en_core_web_sm')
doc = nlp(text)
print([token.text for token in doc])
['Mr.', 'Chen', 'does', "n't", 'agree', 'with', 'my', 'suggestion', '.']

NLTK:

from nltk.tokenize import word_tokenize
from nltk import data
data.path.append('/home/kesci/input/nltk_data3784/nltk_data')
print(word_tokenize(text))
['Mr.', 'Chen', 'does', "n't", 'agree', 'with', 'my', 'suggestion', '.']

L4文本预处理的更多相关文章

  1. 【NLP】Tika 文本预处理:抽取各种格式文件内容

    Tika常见格式文件抽取内容并做预处理 作者 白宁超 2016年3月30日18:57:08 摘要:本文主要针对自然语言处理(NLP)过程中,重要基础部分抽取文本内容的预处理.首先我们要意识到预处理的重 ...

  2. Keras文本预处理

    学习了Keras文档里的文本预处理部分,参考网上代码写了个例子 import keras.preprocessing.text as T from keras.preprocessing.text i ...

  3. [ DLPytorch ] 文本预处理&语言模型&循环神经网络基础

    文本预处理 实现步骤(处理语言模型数据集距离) 文本预处理的实现步骤 读入文本:读入zip / txt 等数据集 with zipfile.ZipFile('./jaychou_lyrics.txt. ...

  4. NLP自然语言处理入门-- 文本预处理Pre-processing

    引言 自然语言处理NLP(nature language processing),顾名思义,就是使用计算机对语言文字进行处理的相关技术以及应用.在对文本做数据分析时,我们一大半的时间都会花在文本预处理 ...

  5. 浅谈NLP 文本分类/情感分析 任务中的文本预处理工作

    目录 浅谈NLP 文本分类/情感分析 任务中的文本预处理工作 前言 NLP相关的文本预处理 浅谈NLP 文本分类/情感分析 任务中的文本预处理工作 前言 之所以心血来潮想写这篇博客,是因为最近在关注N ...

  6. 学习笔记--python中使用多进程、多线程加速文本预处理

    一.任务描述 最近尝试自行构建skip-gram模型训练word2vec词向量表.其中有一步需要统计各词汇的出现频率,截取出现频率最高的10000个词汇进行保留,形成常用词词典.对于这个问题,我建立了 ...

  7. NLP 文本预处理

    1.不同类别文本量统计,类别不平衡差异 2.文本长度统计 3.文本处理,比如文本语料中简体与繁体共存,这会加大模型的学习难度.因此,他们对数据进行繁体转简体的处理. 同时,过滤掉了对分类没有任何作用的 ...

  8. Python3实现文本预处理

    1.数据集准备 测试数据集下载:https://github.com/Asia-Lee/Vulnerability_classify/blob/master/testdata.xls 停用词过滤表下载 ...

  9. python 参议院文本预处理的一维数组的间隔空间

    #!/usr/bin/python import re def pre_process_msg ( msgIn ):     if msgIn=="":         retur ...

随机推荐

  1. django之 F与Q查询

    F与Q查询 F查询 why?

  2. SpringCloud系列之服务注册发现(Eureka)应用篇

    @ 目录 前言 项目版本 Eureka服务端 Eureka客户端 服务访问 前言 大家好,距离上周发布的配置中心基础使用已过去差不多一周啦,趁着周末继续完善后续SpringCloud组件的集成,本次代 ...

  3. 「SWTR-04」Sweet Round 04 游记

    比赛链接 由于 \(\texttt{Sweet Round}\) 比赛挺好的(关键不知道为啥\(Unrated\) 开篇总结(大雾):这次比赛题目不错(有思维含量) 尽管我不会做. 我一看 \(T1\ ...

  4. AQS源码详细解读

    AQS源码详细解读 目录 AQS源码详细解读 基础 CAS相关知识 通过标识位进行线程挂起的并发编程范式 MPSC队列的实现技巧 代码讲解 独占模式 独占模式下请求资源 独占模式下的释放资源 共享模式 ...

  5. Transformers 词汇表 | 二

    作者|huggingface 编译|VK 来源|Github 词汇表每种模型都不同,但与其他模型相似.因此,大多数模型使用相同的输入,此处将在用法示例中进行详细说明. 输入ID 输入id通常是传递给模 ...

  6. SpringCloud服务的注册发现--------consul实现服务与发现

    1,consul也可以替代Eureka实现注册和发现的功能,即注册中心. 之前在linux环境通过consul + upsync + nginx 实现nginx 的动态负载均衡 https://www ...

  7. 2.1.JVM的垃圾回收机制,判断对象是否死亡

    因为热爱,所以坚持. 文章下方有本文参考电子书和视频的下载地址哦~ 这节我们主要讲垃圾收集的一些基本概念,先了解垃圾收集是什么.然后触发条件是什么.最后虚拟机如何判断对象是否死亡. 一.前言   我们 ...

  8. layuiadmin使用Ueditor 获取不了数据的解决方法

    表单根元素请使用form元素,layuiadmin 默认使用div作为表单根元素. <form class="layui-form"> <textarea nam ...

  9. BFS、DFS ——J - Nightmare

    J - Nightmare Ignatius had a nightmare last night. He found himself in a labyrinth with a time bomb ...

  10. 技术再深入一点又何妨?一脸懵B的聊Actor

    记得上次深入 Resin 源码时,见到了Actor 字眼,当时主要从 Resin 中抽取关键架构,就屏蔽了 Actor 相关代码.未曾想这两天研究 flink 的运行架构以及源码,再次与 Actor ...