簡體   English   中英

具有相同“列表”類型的兩個列表之間的區別(帶和不帶撇號'')--python

[英]Difference between two list with same 'list' type (with and without apostrophe ' ')--python

我有兩個列表,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))

Output:

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)

謝謝!

看起來 spacy 給你一個 object,而不僅僅是文本......當你使用 nlp 時,試試:

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

這應該會給你一個你正在尋找的 str 到 str 的比較。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM