NLTK的XMLCorpusReader可用于多文件语料库吗?

NAD*_*NAD 3 python xml nlp nltk

我正在尝试使用NLTK在New York Times Annotated Corpus上做一些工作,其中包含每篇文章的XML文件(新闻行业文本格式NITF).

我可以解析单个文档,没有问题,如下:

from nltk.corpus.reader import XMLCorpusReader
reader = XMLCorpusReader('nltk_data/corpora/nytimes/1987/01/01', r'0000000.xml')
Run Code Online (Sandbox Code Playgroud)

我需要在整个语料库上工作.我试过这样做:

reader = XMLCorpusReader('corpora/nytimes', r'.*')
Run Code Online (Sandbox Code Playgroud)

但这不会创建一个可用的读者对象.例如

len(reader.words())
Run Code Online (Sandbox Code Playgroud)

回报

raise TypeError('Expected a single file identifier string')
TypeError: Expected a single file identifier string
Run Code Online (Sandbox Code Playgroud)

如何将此语料库读入NLTK?

我是NLTK的新手,所以非常感谢任何帮助.

mac*_*ing 5

我不是NLTK专家,所以可能有一种更简单的方法来做到这一点,但天真地我建议你使用Python的glob模块.它支持Unix-stle路径名模式扩展.

from glob import glob
texts = glob('nltk_data/corpora/nytimes/*')
Run Code Online (Sandbox Code Playgroud)

这样就会以列表形式给出与指定表达式匹配的文件的名称.然后,根据您想要/需要一次打开多少个,您可以:

from nltk.corpus.reader import XMLCorpusReader
for item_path in texts:
    reader = XMLCorpusReader('nltk_data/corpora/nytimes/', item_path)
Run Code Online (Sandbox Code Playgroud)

正如@waffle paradox所建议的那样:你也可以texts根据你的特定需求来减少这个列表.