python - 使用 NLTK 创建新语料库

标签 python nlp nltk corpus

我认为我标题的答案通常是去阅读文档,但我浏览了 NLTK book但它没有给出答案。我对 Python 有点陌生。

我有一堆 .txt 文件,我希望能够使用 NLTK 为语料库 nltk_data 提供的语料库函数。

我已经尝试过 PlaintextCorpusReader 但我无法做到:

>>>import nltk
>>>from nltk.corpus import PlaintextCorpusReader
>>>corpus_root = './'
>>>newcorpus = PlaintextCorpusReader(corpus_root, '.*')
>>>newcorpus.words()

如何使用 punkt 分割 newcorpus 句子?我尝试使用 punkt 函数,但 punkt 函数无法读取 PlaintextCorpusReader 类?

您能否指导我如何将分段数据写入文本文件?

最佳答案

经过几年的摸索,这里是

的更新教程

如何创建带有文本文件目录的 NLTK 语料库?

主要思想是利用 nltk.corpus.reader包裹。如果您有 English 的文本文件目录,最好使用 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 调用的 word tokenizationsentence tokenization接受字符串/基本字符串输入并产生此类输出的模块:

>>> 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', '.']

关于python - 使用 NLTK 创建新语料库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4951751/

相关文章:

python - 根据自定义字典对字符串进行分词

python - "continuous"在 Pygame 中绘图

c++ - 图书馆从文本中发现日期?

python - 如何在词嵌入模型中添加 OOV 术语

python - 机器学习实体候选评分(非识别)

python - 如何安装和调用 Stanford NERTagger?

python - 保存 FITS 表 : The keyword description with its value is too long

python - 尝试使用 urllib3 和 json 获取烂番茄数据时出错(Python)

python - 以最少的数据使用量推送通知

python - 尝试从 nltk 获取首字母缩略词