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

2024-09-22 14:39:31 发布

您现在位置:Python中文网/ 问答频道 /正文

我正试图使用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')

不过,我需要研究整个语料库。 我试着这么做:

^{pr2}$

但这并没有创建一个可用的reader对象。例如

len(reader.words())

退货

raise TypeError('Expected a single file identifier string')
TypeError: Expected a single file identifier string

如何将这些语料读入NLTK?在

我是NLTK新手,所以非常感谢您的帮助。在


Tags: newstringreaderfileexpectedannotatedidentifiertimes
3条回答

我不是NLTK专家,所以可能有一种更简单的方法来实现这一点,但我天真地建议您使用Python's ^{} module。它支持Unix stle路径名模式扩展。在

from glob import glob
texts = glob('nltk_data/corpora/nytimes/*')

这样就可以以列表形式给出与指定表达式匹配的文件名。 然后,根据您希望/需要一次打开的数量,您可以:

^{pr2}$

正如@waffle paradox:所建议的那样,您还可以将texts的列表缩减以满足您的特定需求。在

这是一个基于机器渴望和华夫悖论评论的解决方案。 使用glob生成项目列表,并将它们作为列表传递给XMLCorpusReader:

from glob import glob
import re
years = glob('nltk_data/corpora/nytimes_test/*')
year_months = []
for year in years:
    year_months += glob(year+'/*')
    print year_months
days = []
for year_month in year_months:
    days += glob(year_month+'/*')
articles = []
for day in days:
    articles += glob(day+'/*.xml')
file_ids = []
for article in articles:
    file_ids.append(re.sub('nltk_data/corpora/nytimes_test','',article))
reader = XMLCorpusReader('nltk_data/corpora/nytimes_test', articles)

可以指定多个文件。(发件人:http://nltk.googlecode.com/svn/trunk/doc/api/nltk.corpus.reader.xmldocs.XMLCorpusReader-class.html

这里的问题是,我怀疑所有的文件都包含在一个文件结构中,沿着corpora/nytimes/year/month/date的行。XMLCorpusReader不会递归地遍历目录。i、 例如,使用上面的代码XMLCorpusReader('corpora/nytimes', r'.*'),XMLCorpusReader只看到corpora/nytimes/中的xml文件(即,没有,因为只有文件夹),而不是{}可能包含的任何子文件夹中。此外,您可能打算使用*.xml作为第二个参数。在

我建议您自己遍历这些文件夹来构建绝对路径(上面的文档指定fileids参数的显式路径将起作用),或者如果您有可用的年/月/日组合列表,那么就可以利用它。在

相关问题 更多 >