经过数年弄清楚其工作原理后,这是
如何使用文本文件目录创建NLTK语料库?
主要思想是利用nltk.corpus.reader包。如果您有英文文本文件目录,则最好使用PlaintextCorpusReader。
如果您的目录如下所示:
newcorpus/
file1.txt
file2.txt
...
只需使用以下代码行,您就可以得到一个语料库:
import os
from nltk.corpus.reader.plaintext import PlaintextCorpusReader
corpusdir = 'newcorpus/'
newcorpus = PlaintextCorpusReader(corpusdir, '.*')
注意:该PlaintextCorpusReader
将会使用默认设置,nltk.tokenize.sent_tokenize()
并将nltk.tokenize.word_tokenize()
您的文本分为句子和单词,并且这些功能是针对英语构建的,可能不适用于所有语言。
这是创建测试文本文件的完整代码,以及如何使用NLTK创建语料库以及如何在不同级别访问语料库:
import os
from nltk.corpus.reader.plaintext import PlaintextCorpusReader
txt1 = """This is a foo bar sentence.\nAnd this is the first txtfile in the corpus."""
txt2 = """Are you a foo bar? Yes I am. Possibly, everyone is.\n"""
corpus = [txt1,txt2]
corpusdir = 'newcorpus/'
if not os.path.isdir(corpusdir):
os.mkdir(corpusdir)
filename = 0
for text in corpus:
filename+=1
with open(corpusdir+str(filename)+'.txt','w') as fout:
print>>fout, text
assert os.path.isdir(corpusdir)
for infile, text in zip(sorted(os.listdir(corpusdir)),corpus):
assert open(corpusdir+infile,'r').read().strip() == text.strip()
newcorpus = PlaintextCorpusReader('newcorpus/', '.*')
for infile in sorted(newcorpus.fileids()):
print infile
with newcorpus.open(infile) as fin:
print fin.read().strip()
print
print newcorpus.raw().strip()
print
print newcorpus.paras()
print
print newcorpus.paras(newcorpus.fileids()[0])
print newcorpus.sents()
print
print newcorpus.sents(newcorpus.fileids()[0])
print newcorpus.words()
print newcorpus.words(newcorpus.fileids()[0])
最后,要阅读文本目录并创建其他语言的NLTK语料库,必须首先确保您拥有一个python可调用的单词标记化和句子标记化模块,这些模块接受字符串/基字符串输入并产生以下输出:
>>> from nltk.tokenize import sent_tokenize, word_tokenize
>>> txt1 = """This is a foo bar sentence.\nAnd this is the first txtfile in the corpus."""
>>> sent_tokenize(txt1)
['This is a foo bar sentence.', 'And this is the first txtfile in the corpus.']
>>> word_tokenize(sent_tokenize(txt1)[0])
['This', 'is', 'a', 'foo', 'bar', 'sentence', '.']