我正在尝试使用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')
我需要在整个语料库上工作。 我试过这样做:
reader = XMLCorpusReader('corpora/nytimes', r'.*')
但这不会创建一个可用的读者对象。例如
len(reader.words())
返回
raise TypeError('Expected a single file identifier string')
TypeError: Expected a single file identifier string
如何将此语料库读入NLTK?
我是NLTK的新手,所以非常感谢任何帮助。
答案 0 :(得分:5)
我不是NLTK专家,所以可能有一种更简单的方法可以做到这一点,但我天真地建议您使用Python's glob
module。它支持Unix-stle路径名模式扩展。
from glob import glob
texts = glob('nltk_data/corpora/nytimes/*')
这样就会以list-form的形式给出与指定表达式匹配的文件的名称。 然后,根据您想要/需要一次打开多少个,您可以这样做:
from nltk.corpus.reader import XMLCorpusReader
for item_path in texts:
reader = XMLCorpusReader('nltk_data/corpora/nytimes/', item_path)
根据@waffle paradox:的建议,你也可以缩小texts
的这个列表,以满足你的特定需求。
答案 1 :(得分:4)
这是基于机器向往和华夫饼悖论评论的解决方案。 使用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)
答案 2 :(得分:3)
是的,您可以指定多个文件。 (来自:http://nltk.googlecode.com/svn/trunk/doc/api/nltk.corpus.reader.xmldocs.XMLCorpusReader-class.html)
这里的问题是我怀疑你的所有文件都包含在corpora/nytimes/year/month/date
行的文件结构中。 XMLCorpusReader不会递归遍历目录。即,使用上面的代码XMLCorpusReader('corpora/nytimes', r'.*')
,XMLCorpusReader只能看到corpora/nytimes/
中的xml文件(即,没有,因为只有文件夹),而不是corpora/nytimes
可能包含的任何子文件夹。此外,您可能打算使用*.xml
作为第二个参数。
我建议您自己遍历文件夹以构建绝对路径(上面的文档指定fileids
参数的显式路径将起作用),或者如果您有可用的年/月/日组合列表,使用它对您有利。