使用 NLTK 对文本进行清洗,索引工具

EN_WHITELIST = '0123456789abcdefghijklmnopqrstuvwxyz ' # space is included in whitelist
EN_BLACKLIST = '!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~\'' FILENAME = 'data/chat.txt' limit = {
'maxq' : 20,
'minq' : 0,
'maxa' : 20,
'mina' : 3
} UNK = 'unk'
VOCAB_SIZE = 6000 import random
import sys import nltk
import itertools
from collections import defaultdict import numpy as np import pickle def ddefault():
return 1 '''
read lines from file
return [list of lines] '''
def read_lines(filename):
return open(filename).read().split('\n')[:-1] '''
split sentences in one line
into multiple lines
return [list of lines] '''
def split_line(line):
return line.split('.') '''
remove anything that isn't in the vocabulary
return str(pure ta/en) '''
def filter_line(line, whitelist):
return ''.join([ ch for ch in line if ch in whitelist ]) '''
read list of words, create index to word,
word to index dictionaries
return tuple( vocab->(word, count), idx2w, w2idx ) '''
def index_(tokenized_sentences, vocab_size):
# get frequency distribution
freq_dist = nltk.FreqDist(itertools.chain(*tokenized_sentences))
# get vocabulary of 'vocab_size' most used words
vocab = freq_dist.most_common(vocab_size)
# index2word
index2word = ['_'] + [UNK] + [ x[0] for x in vocab ]
# word2index
word2index = dict([(w,i) for i,w in enumerate(index2word)] )
return index2word, word2index, freq_dist '''
filter too long and too short sequences
return tuple( filtered_ta, filtered_en ) '''
def filter_data(sequences):
filtered_q, filtered_a = [], []
raw_data_len = len(sequences)//2 for i in range(0, len(sequences), 2):
qlen, alen = len(sequences[i].split(' ')), len(sequences[i+1].split(' '))
if qlen >= limit['minq'] and qlen <= limit['maxq']:
if alen >= limit['mina'] and alen <= limit['maxa']:
filtered_q.append(sequences[i])
filtered_a.append(sequences[i+1]) # print the fraction of the original data, filtered
filt_data_len = len(filtered_q)
filtered = int((raw_data_len - filt_data_len)*100/raw_data_len)
print(str(filtered) + '% filtered from original data') return filtered_q, filtered_a '''
create the final dataset :
- convert list of items to arrays of indices
- add zero padding
return ( [array_en([indices]), array_ta([indices]) ) '''
def zero_pad(qtokenized, atokenized, w2idx):
# num of rows
data_len = len(qtokenized) # numpy arrays to store indices
idx_q = np.zeros([data_len, limit['maxq']], dtype=np.int32)
idx_a = np.zeros([data_len, limit['maxa']], dtype=np.int32) for i in range(data_len):
q_indices = pad_seq(qtokenized[i], w2idx, limit['maxq'])
a_indices = pad_seq(atokenized[i], w2idx, limit['maxa']) #print(len(idx_q[i]), len(q_indices))
#print(len(idx_a[i]), len(a_indices))
idx_q[i] = np.array(q_indices)
idx_a[i] = np.array(a_indices) return idx_q, idx_a '''
replace words with indices in a sequence
replace with unknown if word not in lookup
return [list of indices] '''
def pad_seq(seq, lookup, maxlen):
indices = []
for word in seq:
if word in lookup:
indices.append(lookup[word])
else:
indices.append(lookup[UNK])
return indices + [0]*(maxlen - len(seq)) def process_data(): print('\n>> Read lines from file')
lines = read_lines(filename=FILENAME) # change to lower case (just for en)
lines = [ line.lower() for line in lines ] print('\n:: Sample from read(p) lines')
print(lines[121:125]) # filter out unnecessary characters
print('\n>> Filter lines')
lines = [ filter_line(line, EN_WHITELIST) for line in lines ]
print(lines[121:125]) # filter out too long or too short sequences
print('\n>> 2nd layer of filtering')
qlines, alines = filter_data(lines)
print('\nq : {0} ; a : {1}'.format(qlines[60], alines[60]))
print('\nq : {0} ; a : {1}'.format(qlines[61], alines[61])) # convert list of [lines of text] into list of [list of words ]
print('\n>> Segment lines into words')
qtokenized = [ wordlist.split(' ') for wordlist in qlines ]
atokenized = [ wordlist.split(' ') for wordlist in alines ]
print('\n:: Sample from segmented list of words')
print('\nq : {0} ; a : {1}'.format(qtokenized[60], atokenized[60]))
print('\nq : {0} ; a : {1}'.format(qtokenized[61], atokenized[61])) # indexing -> idx2w, w2idx : en/ta
print('\n >> Index words')
idx2w, w2idx, freq_dist = index_( qtokenized + atokenized, vocab_size=VOCAB_SIZE) print('\n >> Zero Padding')
idx_q, idx_a = zero_pad(qtokenized, atokenized, w2idx) print('\n >> Save numpy arrays to disk')
# save them
np.save('idx_q.npy', idx_q)
np.save('idx_a.npy', idx_a) # let us now save the necessary dictionaries
metadata = {
'w2idx' : w2idx,
'idx2w' : idx2w,
'limit' : limit,
'freq_dist' : freq_dist
} # write to disk : data control dictionaries
with open('metadata.pkl', 'wb') as f:
pickle.dump(metadata, f) def load_data(PATH=''):
# read data control dictionaries
with open(PATH + 'metadata.pkl', 'rb') as f:
metadata = pickle.load(f)
# read numpy arrays
idx_ta = np.load(PATH + 'idx_q.npy')
idx_en = np.load(PATH + 'idx_a.npy')
return metadata, idx_q, idx_a if __name__ == '__main__':
process_data()

使用 NLTK 对文本进行清洗,索引工具的更多相关文章

  1. 【NLP】Python NLTK获取文本语料和词汇资源

    Python NLTK 获取文本语料和词汇资源 作者:白宁超 2016年11月7日13:15:24 摘要:NLTK是由宾夕法尼亚大学计算机和信息科学使用python语言实现的一种自然语言工具包,其收集 ...

  2. bash文本查看及处理工具

    文本查看及处理工具:     wc [OPTION] FILE...         -c: 字节数         -l:行数         -w: 单词数             who | w ...

  3. js实现去文本换行符小工具

    js实现去文本换行符小工具 一.总结 一句话总结: 1.vertical属性使用的时候注意看清定义,也注意父元素的基准线问题.vertical-align:top; 2.获取textareaEleme ...

  4. 基于COCA词频表的文本词汇分布测试工具v0.1

    美国语言协会对美国人日常使用的英语单词做了一份详细的统计,按照日常使用的频率做成了一张表,称为COCA词频表.排名越低的单词使用频率越高,该表可以用来统计词汇量. 如果你的词汇量约为6000,那么这张 ...

  5. MySQL检查重复索引工具-pt-duplicate-key-checker

    在MySQL中是允许在同一个列上创建多个索引的,示例如下: mysql --socket=/tmp/mysql5173.sock -uroot -p mysql> SELECT VERSION( ...

  6. Linux Shell处理文本最常用的工具大盘点

    导读 本文将介绍Linux下使用Shell处理文本时最常用的工具:find.grep.xargs.sort.uniq.tr.cut.paste.wc.sed.awk:提供的例子和参数都是最常用和最为实 ...

  7. NLTK和Stanford NLP两个工具的安装配置

    这里安装的是两个自然语言处理工具,NLTK和Stanford NLP. 声明:笔者操作系统是Windows10,理论上Windows都可以: 版本号:NLTK 3.2 Stanford NLP 3.6 ...

  8. 谈谈开发文本转URL小工具的思路

    URL提供了一种定位互联网上任意资源的手段,由于采用HTTP协议的URL能在互联网上自由传播和使用,所以能大行其道.在软件开发.测试甚至部署的环节,URL几乎可以说无处不再,其中用来定位文本的URL数 ...

  9. nltk处理文本

    nltk(Natural Language Toolkit)是处理文本的利器. 安装 pip install nltk 进入python命令行,键入nltk.download()可以下载nltk需要的 ...

随机推荐

  1. 对话|首席研究员童欣:从长远看,AR的应用范围远比VR广泛

    ​童欣博士现任微软亚洲研究院网络图形组首席研究员.1993年毕业于浙江大学计算机系,获工学学士学位:1996年获浙江大学计算机系硕士学位:1999年获清华大学计算机系博士学位,同年加入微软亚洲研究院. ...

  2. python中使用paramiko模块并实现远程连接服务器执行上传下载

    paramiko模块 paramiko是用python语言写的一个模块,遵循SSH2协议,支持以加密和认证的方式,进行远程服务器的连接. 因此,如果需要使用SSH从一个平台连接到另外一个平台,进行一系 ...

  3. Redis list实现原理 - 双向循环链表

    双向链表 双向表示每个节点知道自己的直接前驱和直接后继,每个节点需要三个域 查找方向可以是从左往右也可以是从右往左,但是要实现从右往左还需要终端节点的地址,所以通常会设计成双向的循环链表; 双向的循环 ...

  4. maven笔记--持续更新

    笔记: 在创建maven项目的时候,如果用到servlet的时候,需要导入包,这时候,需要导入本地仓库的jar包,即依赖包.语法如下 <dependency> <groupId> ...

  5. Typora[MarkDown编辑器]+(PicGo+Github+JsDelivr)[个人图床] ,开启你的高效创作

    使用Typora搭配Picgo开启你的高效创作 0x00 一切都要从MarkDown说起 富文本语言的弊端 平常我们最常用的写作工具,无非是富文本编辑器中的代表--微软家的Office Word.这种 ...

  6. 分布式图数据库 Nebula Graph 的 Index 实践

    导读 索引是数据库系统中不可或缺的一个功能,数据库索引好比是书的目录,能加快数据库的查询速度,其实质是数据库管理系统中一个排序的数据结构.不同的数据库系统有不同的排序结构,目前常见的索引实现类型如 B ...

  7. openwrt MT7620A MT7610E 5G 驱动添加移值

    使用 github 上别人提供好的源码.整合到最新的 openwrt 18 中,目前 kernel 的版本为 4.1 . 编辑中....

  8. Redis03——Redis是如何删除你的数据的

    众所周知Redis针对每一个key都能单独设置过期时间,那么Redis是怎么处理这些key的过期时间的呢?当同一时间有大量Key同时到期时,Redis又是怎么处理的呢?会不会影响到我的线上业务呢?如果 ...

  9. nuxt.js如何实现同级目录下建多个动态路由,并将链接设置.html后缀

    nuxt.js中如果在同级目录中建两个_xxxx.vue的动态路由文件,那么页面跳转始终是跳的一个页面,如何解决这个问题呢?下面举个栗子: 第一步:新建两个页面文件 第二步:在nuxt.config. ...

  10. Android开发走过的坑(持续更新)

    1 华为 nova真机 打印不出Log 参考资料:http://www.apkbus.com/thread-585228-1-1.html 解决:针对权限问题,我们当然也可以解决的,华为手机在你的拨号 ...