Python NLTK练习:第5章
Hy guys, 我开始在NLTK团队的官方书籍之后学习NLTK。Python NLTK练习:第5章
我在5章“标记” - 我不能在PDF版186页解决excercises之一:
鉴于CFD2 ['VN指定过去分词名单'] .keys(),尝试收集紧接该列表中项目之前的所有字标记对的列表。
我试着这样说:
wsj = nltk.corpus.treebank.tagged_words(simplify_tags=True)
[wsj[wsj.index((word,tag))-1:wsj.index((word,tag))+1] for (word,tag) in wsj if word in cfd2['VN'].keys()]
,但它给了我这个错误:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/local/lib/python2.7/dist-packages/nltk/corpus/reader/util.py", line 401, in iterate_from
for tok in piece.iterate_from(max(0, start_tok-offset)):
File "/usr/local/lib/python2.7/dist-packages/nltk/corpus/reader/util.py", line 295, in iterate_from
self._stream.seek(filepos)
AttributeError: 'NoneType' object has no attribute 'seek'
我觉得我做错了什么在访问华尔街日报结构,但我不能弄清楚什么是错的!
你能帮我吗?
在此先感谢!
wsj
是nltk.corpus.reader.util.ConcatenatedCorpusView
型表现得像一个列表(这就是为什么你可以使用功能,如index()
),但“幕后” NLTK从不读取整个表到内存中,它只会从文件中读取这些部分它需要的对象。看起来如果你在一个CorpusView对象上迭代并且使用index()
(它需要再次迭代),那么该文件对象将返回None
。
这样,它的工作原理,但它比列表理解那么优雅:
for i in range(len(wsj)):
if wsj[i][0] in cfd2['VN'].keys():
print wsj[(i-1):(i+1)]
貌似这两个指数认购及切分导致异常:
wsj = nltk.corpus.treebank.tagged_words(simplify_tags=True)
cfd2 = nltk.ConditionalFreqDist((t,w) for w,t in wsj)
wanted = cfd2['VN'].keys()
# just getting the index -> exception before 60 items
for w, t in wsj:
if w in wanted:
print wsj.index((w,t))
# just slicing -> sometimes finishes, sometimes throws exception
for i, (w,t) in enumerate(wsj):
if w in wanted:
print wsj[i-1:i+1]
我猜它是通过访问您遍历流以前的项目造成的。
,如果你遍历一旦超过wsj
创建索引列表,并使用他们的第二次迭代抢切片它工作正常:
results = [
wsj[j-1:j+1]
for j in [
i for i, (w,t) in enumerate(wsj)
if w in wanted
]
]
补充说明:调用index
没有start
论证会每次返回第一场比赛。
wsj
为ConcatenatedCorpusView
类型的,我认为这是一个空的元组('.', '.')
窒息。最简单的解决方案是将ConcatenatedCorpusView
明确地转换为list
。你可以通过做:
wsj = list(wsj)
迭代工作正常即可。获取重复项目的索引是一个单独的问题。请参阅:https://gist.github.com/denten/11388676
谢谢,它的工作原理! – 2013-05-02 20:14:45