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

  1. EN_WHITELIST = '0123456789abcdefghijklmnopqrstuvwxyz ' # space is included in whitelist
  2. EN_BLACKLIST = '!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~\''
  3. FILENAME = 'data/chat.txt'
  4. limit = {
  5. 'maxq' : 20,
  6. 'minq' : 0,
  7. 'maxa' : 20,
  8. 'mina' : 3
  9. }
  10. UNK = 'unk'
  11. VOCAB_SIZE = 6000
  12. import random
  13. import sys
  14. import nltk
  15. import itertools
  16. from collections import defaultdict
  17. import numpy as np
  18. import pickle
  19. def ddefault():
  20. return 1
  21. '''
  22. read lines from file
  23. return [list of lines]
  24. '''
  25. def read_lines(filename):
  26. return open(filename).read().split('\n')[:-1]
  27. '''
  28. split sentences in one line
  29. into multiple lines
  30. return [list of lines]
  31. '''
  32. def split_line(line):
  33. return line.split('.')
  34. '''
  35. remove anything that isn't in the vocabulary
  36. return str(pure ta/en)
  37. '''
  38. def filter_line(line, whitelist):
  39. return ''.join([ ch for ch in line if ch in whitelist ])
  40. '''
  41. read list of words, create index to word,
  42. word to index dictionaries
  43. return tuple( vocab->(word, count), idx2w, w2idx )
  44. '''
  45. def index_(tokenized_sentences, vocab_size):
  46. # get frequency distribution
  47. freq_dist = nltk.FreqDist(itertools.chain(*tokenized_sentences))
  48. # get vocabulary of 'vocab_size' most used words
  49. vocab = freq_dist.most_common(vocab_size)
  50. # index2word
  51. index2word = ['_'] + [UNK] + [ x[0] for x in vocab ]
  52. # word2index
  53. word2index = dict([(w,i) for i,w in enumerate(index2word)] )
  54. return index2word, word2index, freq_dist
  55. '''
  56. filter too long and too short sequences
  57. return tuple( filtered_ta, filtered_en )
  58. '''
  59. def filter_data(sequences):
  60. filtered_q, filtered_a = [], []
  61. raw_data_len = len(sequences)//2
  62. for i in range(0, len(sequences), 2):
  63. qlen, alen = len(sequences[i].split(' ')), len(sequences[i+1].split(' '))
  64. if qlen >= limit['minq'] and qlen <= limit['maxq']:
  65. if alen >= limit['mina'] and alen <= limit['maxa']:
  66. filtered_q.append(sequences[i])
  67. filtered_a.append(sequences[i+1])
  68. # print the fraction of the original data, filtered
  69. filt_data_len = len(filtered_q)
  70. filtered = int((raw_data_len - filt_data_len)*100/raw_data_len)
  71. print(str(filtered) + '% filtered from original data')
  72. return filtered_q, filtered_a
  73. '''
  74. create the final dataset :
  75. - convert list of items to arrays of indices
  76. - add zero padding
  77. return ( [array_en([indices]), array_ta([indices]) )
  78. '''
  79. def zero_pad(qtokenized, atokenized, w2idx):
  80. # num of rows
  81. data_len = len(qtokenized)
  82. # numpy arrays to store indices
  83. idx_q = np.zeros([data_len, limit['maxq']], dtype=np.int32)
  84. idx_a = np.zeros([data_len, limit['maxa']], dtype=np.int32)
  85. for i in range(data_len):
  86. q_indices = pad_seq(qtokenized[i], w2idx, limit['maxq'])
  87. a_indices = pad_seq(atokenized[i], w2idx, limit['maxa'])
  88. #print(len(idx_q[i]), len(q_indices))
  89. #print(len(idx_a[i]), len(a_indices))
  90. idx_q[i] = np.array(q_indices)
  91. idx_a[i] = np.array(a_indices)
  92. return idx_q, idx_a
  93. '''
  94. replace words with indices in a sequence
  95. replace with unknown if word not in lookup
  96. return [list of indices]
  97. '''
  98. def pad_seq(seq, lookup, maxlen):
  99. indices = []
  100. for word in seq:
  101. if word in lookup:
  102. indices.append(lookup[word])
  103. else:
  104. indices.append(lookup[UNK])
  105. return indices + [0]*(maxlen - len(seq))
  106. def process_data():
  107. print('\n>> Read lines from file')
  108. lines = read_lines(filename=FILENAME)
  109. # change to lower case (just for en)
  110. lines = [ line.lower() for line in lines ]
  111. print('\n:: Sample from read(p) lines')
  112. print(lines[121:125])
  113. # filter out unnecessary characters
  114. print('\n>> Filter lines')
  115. lines = [ filter_line(line, EN_WHITELIST) for line in lines ]
  116. print(lines[121:125])
  117. # filter out too long or too short sequences
  118. print('\n>> 2nd layer of filtering')
  119. qlines, alines = filter_data(lines)
  120. print('\nq : {0} ; a : {1}'.format(qlines[60], alines[60]))
  121. print('\nq : {0} ; a : {1}'.format(qlines[61], alines[61]))
  122. # convert list of [lines of text] into list of [list of words ]
  123. print('\n>> Segment lines into words')
  124. qtokenized = [ wordlist.split(' ') for wordlist in qlines ]
  125. atokenized = [ wordlist.split(' ') for wordlist in alines ]
  126. print('\n:: Sample from segmented list of words')
  127. print('\nq : {0} ; a : {1}'.format(qtokenized[60], atokenized[60]))
  128. print('\nq : {0} ; a : {1}'.format(qtokenized[61], atokenized[61]))
  129. # indexing -> idx2w, w2idx : en/ta
  130. print('\n >> Index words')
  131. idx2w, w2idx, freq_dist = index_( qtokenized + atokenized, vocab_size=VOCAB_SIZE)
  132. print('\n >> Zero Padding')
  133. idx_q, idx_a = zero_pad(qtokenized, atokenized, w2idx)
  134. print('\n >> Save numpy arrays to disk')
  135. # save them
  136. np.save('idx_q.npy', idx_q)
  137. np.save('idx_a.npy', idx_a)
  138. # let us now save the necessary dictionaries
  139. metadata = {
  140. 'w2idx' : w2idx,
  141. 'idx2w' : idx2w,
  142. 'limit' : limit,
  143. 'freq_dist' : freq_dist
  144. }
  145. # write to disk : data control dictionaries
  146. with open('metadata.pkl', 'wb') as f:
  147. pickle.dump(metadata, f)
  148. def load_data(PATH=''):
  149. # read data control dictionaries
  150. with open(PATH + 'metadata.pkl', 'rb') as f:
  151. metadata = pickle.load(f)
  152. # read numpy arrays
  153. idx_ta = np.load(PATH + 'idx_q.npy')
  154. idx_en = np.load(PATH + 'idx_a.npy')
  155. return metadata, idx_q, idx_a
  156. if __name__ == '__main__':
  157. 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. C++走向远洋——46(教师兼干部类、多重继承、派生)

    */ * Copyright (c) 2016,烟台大学计算机与控制工程学院 * All rights reserved. * 文件名:text.cpp * 作者:常轩 * 微信公众号:Worldhe ...

  2. MUI使用H5+Api调取系统相册多图选择及转base64码

    伟大的哲学家曾说过"写代码,一定要翻文档" 这次我们需要用到的是调取系统相册进行多图上传,先奉上html5+api关于系统相册的文档链接链接:HTML5+ API Referenc ...

  3. vue+element tree(树形控件)组件(1)

    最近做了第一个组内可以使用的组件,虽然是最简版,也废了不少力.各位前辈帮我解决问题,才勉强搞定.让我来记录这个树形组件的编写过程和期间用到的知识点. 首先说说需求,就是点击出现弹窗+蒙板,弹窗内容是一 ...

  4. JS基础入门篇(十八)—日期对象

    1.日期对象 日期对象: 通过new Date()就能创建一个日期对象,这个对象中有当前系统时间的所有详细信息. 以下代码可以获取当前时间: <script> var t = new Da ...

  5. Windows下利用virtualenvwrapper指定python版本创建虚拟环境

    默认已安装virtualenvwrapper 一.添加环境变量(可选) 在系统环境变量中添加 WORKON_HOME ,用来指定新建的虚拟环境的存储位置,如过未添加,默认位置为 %USERPROFIL ...

  6. agent判断用户请求设备

  7. linux命令行界面如何安装图形化界面

    linux命令行界面如何安装图形化界面 目录 问题描述 解决方案 安装包 测试是否安装成功 如何卸载图形化界面 遭遇问题 问题描述 当我们在安装Linux系统时,我们一开始可能安装的是非图形界面的系统 ...

  8. 什么是FHS,Linux的文件系统目录标准是怎样的

    Filesystem Hierarchy Standard(文件系统目录标准)的缩写,多数Linux版本采用这种文件组织形式,类似于Windows操作系统中c盘的文件目录,FHS采用树形结构组织文件. ...

  9. Fortify Audit Workbench 笔记 SQL Injection SQL注入

    SQL Injection SQL注入 Abstract 通过不可信来源的输入构建动态 SQL 指令,攻击者就能够修改指令的含义或者执行任意 SQL 命令. Explanation SQL injec ...

  10. JVM01——JVM内存区域的构成

    从本文开始将为各位带来JVM方面的知识点,关注我的公众号「Java面典」了解更多Java相关知识点. JVM内存主要分为三部分线程私有(Thread Local).线程共享(Thread Shared ...