如果你有自己收集的文本文件,并且想使用nltk带的方式访问或者处理,你可以很容易地在NLTK 中的PlaintextCorpusReader 帮助下载入它们。检查你的文件在文件系统中的位置;在下面的例子中,我们假定你的文件在E:\datadata目录下(假如目录下有两个文件)。不管是什么位置,将变量corpus_root的值设置为这个目录。PlaintextCorpusReader 初始化函数的第二个参数可以是一个如['a.txt', 'test/b.txt']这样的fileids
链表,或者一个匹配所有fileids 的模式,
其余的可参考:
如:'[abc]/.*\.txt'。
from nltk.corpus import PlaintextCorpusReader
corpus_root = 'E:\\datadata'
wordlists = PlaintextCorpusReader(corpus_root, '.*')
wordlists.fileids()
结果是:
['1.txt', '2.txt']
访问指定文件的原始内容:
raw = wordlists.raw('1.txt')
raw
看到1.txt的内容了。
访问整个语料库的词汇:
word = wordlist.words()
其余的可参考:
示例 描述
fileids() 语料库中的文件
fileids([categories]) 这些分类对应的语料库中的文件
categories() 语料库中的分类
categories([fileids]) 这些文件对应的语料库中的分类
raw() 语料库的原始内容
raw(fileids=[f1,f2,f3]) 指定文件的原始内容
raw(categories=[c1,c2]) 指定分类的原始内容
words() 整个语料库中的词汇
words(fileids=[f1,f2,f3]) 指定文件中的词汇
words(categories=[c1]) 指定分类中的词汇
sents() 指定分类中的句子
sents(fileids=[f1,f2,f3]) 指定文件中的句子
sents(categories=[c1]) 指定分类中的句子
abspath(fileid) 指定文件在磁盘上的位置
encoding(fileid) 文件的编码(如果知道的话)
open(fileid) 打开指定语料库文件的文件流
root() 到本地安装的语料库根目录的路径