问题描述
我有一个标记为 token/tag 格式的文件,我尝试了一个函数,该函数返回一个包含 (word,tag) 列表中的单词的元组.
def text_from_tagged_ngram(ngram):如果类型(ngram)==元组:返回 ngram[0]return " ".join(zip(*ngram)[0]) # zip(*ngram)[0] 返回一个包含 (word,tag) 列表中的单词的元组
在 python 2.7 中它运行良好,但在 python 3.4 中它给了我以下错误:
return " ".join(list[zip(*ngram)[0]])类型错误:zip"对象不可下标
有人可以帮忙吗?
在 Python 2 中,zip
返回一个列表.在 Python 3 中,zip
返回一个可迭代对象目的.但是你可以通过调用 list代码>
,如:
list(zip(...))
在这种情况下,那就是:
list(zip(*ngram))
对于列表,您可以使用索引:
items = list(zip(*ngram))...项目[0]
等等.
但如果你只需要第一个元素,那么你并不严格需要一个列表.你可以只使用 next
.>
在这种情况下,那就是:
next(zip(*ngram))
I have a tagged file in the format token/tag and I try a function that returns a tuple with words from a (word,tag) list.
def text_from_tagged_ngram(ngram):
if type(ngram) == tuple:
return ngram[0]
return " ".join(zip(*ngram)[0]) # zip(*ngram)[0] returns a tuple with words from a (word,tag) list
In python 2.7 it worked well, but in python 3.4 it gives me the following error:
return " ".join(list[zip(*ngram)[0]])
TypeError: 'zip' object is not subscriptable
Can someone help?
In Python 2, zip
returned a list. In Python 3, zip
returns an iterable object. But you can make it into a list just by calling list
, as in:
list(zip(...))
In this case, that would be:
list(zip(*ngram))
With a list, you can use indexing:
items = list(zip(*ngram))
...
items[0]
etc.
But if you only need the first element, then you don't strictly need a list. You could just use next
.
In this case, that would be:
next(zip(*ngram))
这篇关于类型错误:“zip"对象不可下标的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!