【问题标题】:Difference between two list with same 'list' type (with and without apostrophe ' ')--python具有相同“列表”类型的两个列表之间的区别(带和不带撇号'')--python
【发布时间】: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" 后它现在可以工作了-- :)

标签: python list token spacy


【解决方案1】:

看起来 spacy 给了你一个对象,而不仅仅是文本......当你使用 nlp 时,试试:

for i in doc.noun_chunks:
    list_2.append(i.text)

这应该会给你一个你正在寻找的 str 到 str 比较。

【讨论】:

  • 谢谢,这对我有帮助,让我重新考虑.text和span,我之前没有足够关注它们,只是考虑了打印结果,现在我看到了: )
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-09-26
  • 2011-09-06
  • 2019-02-26
  • 2022-07-24
  • 2023-03-08
相关资源
最近更新 更多