【发布时间】:2021-04-22 20:15:48
【问题描述】:
我有两个list,list_1是我直接定义的,另一个是spaCy中的操作生成的,都返回'list'类型,但明显不同,一个带'',一个不带' '。
问题_1:
它们在 python 中是完全相同类型的列表吗?
import sys
import re
import spacy
from spacy.tokens import Token
nlp = spacy.load("en_core_web_sm")
nlp = spacy.load("en_core_web_md")
list_1 = ['apple', 'orange', 'banana', 'this is a dog']
print(list_1, type(list_1))
sentence = 'apple and orange and banana this is a dog'
doc = nlp(sentence)
list_2 = []
for i in doc.noun_chunks:
list_2.append(i)
print(list_2,type(list_2))
输出:
list_1: ['apple', 'orange', 'banana', 'this is a dog'] <class 'list'>
list_2: [apple, orange, banana, a dog] <class 'list'>
问题_2:
如何解决以下错误?
我假设它们完全一样(类型),但是当我将 list_2 用作普通列表时,在下面的代码中,它会返回错误。
for i in list_2:
if "dog" in i:
print(list_2.index(i))
错误:
TypeError Traceback (most recent call last)
<ipython-input-110-6f9c38535050> in <module>
16 print(list_2,type(list_2))
17 for i in list_2:
---> 18 if "dog" in i:
19 print(list_2.index(i))
20
TypeError: Argument 'other' has incorrect type (expected spacy.tokens.token.Token, got str)
谢谢!
【问题讨论】:
-
我不确定
nlp做了什么,但list_1 和list_2 之间的区别在于列表中元素的类型。尝试打印type(list_2[0])和type(list_1[0])以查看差异。 -
谢谢,我就是这么做的,是的,我可以看到 type(list_2[0]) 和 type(list_1[0]) 的类型不同:)
-
好的,下一步,如果你真的想使用
nlp,尝试打印dir(list_2[0]),看看提供了哪些函数可以让你检查每个对象包含的内容。我有一种直觉,如果你问if "dog" in str(i):,它可能会起作用。 (虽然不是 100% 确定) -
非常感谢,是的,在 str(i) 中使用 --if "dog" 后它现在可以工作了-- :)