使用NLTK创建新语料库
我觉得通常解决我标题问题的方法就是去看文档,但我看过了NLTK书籍,里面没有找到答案。我对Python还比较陌生。
我有一堆.txt
文件,我想用NLTK提供的语料库功能来处理这些文件,特别是nltk_data
这个语料库。
我试过PlaintextCorpusReader
,但我没能进一步理解:
>>>import nltk
>>>from nltk.corpus import PlaintextCorpusReader
>>>corpus_root = './'
>>>newcorpus = PlaintextCorpusReader(corpus_root, '.*')
>>>newcorpus.words()
我该如何用punkt来分割newcorpus
的句子?我尝试使用punkt的功能,但它似乎无法读取PlaintextCorpusReader
这个类?
你能告诉我怎么把分割后的数据写入文本文件吗?
4 个回答
在编程中,有时候我们需要让程序在特定的条件下执行某些操作。这就像给程序设定了一些规则,只有当这些规则被满足时,程序才会做出反应。
比如说,你可能想要在用户输入一个数字时,程序才进行计算。如果用户输入的不是数字,程序就应该给出提示,告诉用户输入不正确。这种情况下,我们就需要用到条件判断的语句。
条件判断就像是一个分岔路口,程序会根据你设定的条件选择不同的路径去执行。这样可以让程序更加灵活,能够处理不同的情况。
总之,条件判断是编程中非常重要的一部分,它帮助我们控制程序的行为,让程序能够根据不同的输入做出不同的反应。
>>> import nltk
>>> from nltk.corpus import PlaintextCorpusReader
>>> corpus_root = './'
>>> newcorpus = PlaintextCorpusReader(corpus_root, '.*')
"""
if the ./ dir contains the file my_corpus.txt, then you
can view say all the words it by doing this
"""
>>> newcorpus.words('my_corpus.txt')
经过几年的摸索,下面是更新版的教程,教你如何
用一堆文本文件创建一个NLTK语料库。
主要的思路是利用nltk.corpus.reader这个包。如果你有一个包含英文文本文件的文件夹,最好使用PlaintextCorpusReader。
假设你的文件夹结构是这样的:
newcorpus/
file1.txt
file2.txt
...
只需使用以下几行代码,就可以创建一个语料库:
import os
from nltk.corpus.reader.plaintext import PlaintextCorpusReader
corpusdir = 'newcorpus/' # Directory of corpus.
newcorpus = PlaintextCorpusReader(corpusdir, '.*')
注意: PlaintextCorpusReader
会使用默认的 nltk.tokenize.sent_tokenize()
和 nltk.tokenize.word_tokenize()
来把你的文本分成句子和单词,这些函数是为英语设计的,可能不适用于所有语言。
下面是完整的代码,包括如何创建测试文本文件,以及如何用NLTK创建语料库和在不同层级访问语料库:
import os
from nltk.corpus.reader.plaintext import PlaintextCorpusReader
# Let's create a corpus with 2 texts in different textfile.
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]
# Make new dir for the corpus.
corpusdir = 'newcorpus/'
if not os.path.isdir(corpusdir):
os.mkdir(corpusdir)
# Output the files into the directory.
filename = 0
for text in corpus:
filename+=1
with open(corpusdir+str(filename)+'.txt','w') as fout:
print>>fout, text
# Check that our corpus do exist and the files are correct.
assert os.path.isdir(corpusdir)
for infile, text in zip(sorted(os.listdir(corpusdir)),corpus):
assert open(corpusdir+infile,'r').read().strip() == text.strip()
# Create a new corpus by specifying the parameters
# (1) directory of the new corpus
# (2) the fileids of the corpus
# NOTE: in this case the fileids are simply the filenames.
newcorpus = PlaintextCorpusReader('newcorpus/', '.*')
# Access each file in the corpus.
for infile in sorted(newcorpus.fileids()):
print infile # The fileids of each file.
with newcorpus.open(infile) as fin: # Opens the file.
print fin.read().strip() # Prints the content of the file
print
# Access the plaintext; outputs pure string/basestring.
print newcorpus.raw().strip()
print
# Access paragraphs in the corpus. (list of list of list of strings)
# NOTE: NLTK automatically calls nltk.tokenize.sent_tokenize and
# nltk.tokenize.word_tokenize.
#
# Each element in the outermost list is a paragraph, and
# Each paragraph contains sentence(s), and
# Each sentence contains token(s)
print newcorpus.paras()
print
# To access pargraphs of a specific fileid.
print newcorpus.paras(newcorpus.fileids()[0])
# Access sentences in the corpus. (list of list of strings)
# NOTE: That the texts are flattened into sentences that contains tokens.
print newcorpus.sents()
print
# To access sentences of a specific fileid.
print newcorpus.sents(newcorpus.fileids()[0])
# Access just tokens/words in the corpus. (list of strings)
print newcorpus.words()
# To access tokens of a specific fileid.
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', '.']
我觉得 PlaintextCorpusReader
已经用一个叫做 punkt 的分词器把输入内容分段了,至少如果你的输入语言是英语的话。
def __init__(self, root, fileids,
word_tokenizer=WordPunctTokenizer(),
sent_tokenizer=nltk.data.LazyLoader(
'tokenizers/punkt/english.pickle'),
para_block_reader=read_blankline_block,
encoding='utf8'):
你可以给这个阅读器传入一个单词和句子的分词器,但对于句子分词器,默认的已经是 nltk.data.LazyLoader('tokenizers/punkt/english.pickle')
了。
对于一个单独的字符串,分词器的使用方法如下(详细说明可以在 这里 找到,查看第5节了解 punkt 分词器)。
>>> import nltk.data
>>> text = """
... Punkt knows that the periods in Mr. Smith and Johann S. Bach
... do not mark sentence boundaries. And sometimes sentences
... can start with non-capitalized words. i is a good variable
... name.
... """
>>> tokenizer = nltk.data.load('tokenizers/punkt/english.pickle')
>>> tokenizer.tokenize(text.strip())