使用python比较列表中的字符串

2024-04-29 06:04:10 发布

您现在位置:Python中文网/ 问答频道 /正文

我有两个从服务器数据集的一列中选取的列表

Keywords =(('Nike shoes',),('Adidas shoes',),('Levice Jeans',),('adidas jersey',))

Chats = (('Nike shoes have an offer',),('They are at a discount'),
         ('Nike shoes are the best',),('They have other offers as well',),
         ('They have introduced new shoes which are awesome',))

两个列表的格式与上面的完全相同

我想要第三个列表,它将存储关键字列表中的所有常用词

o/p - list3 = ('Nike Shoes')

我尝试过各种方法,但发现了一些错误,比如“列表值应该是整数,而不是元组”


Tags: 数据服务器列表havearekeywordstheyjersey
2条回答

你可以这样做:

Keywords =(('Nike shoes',),('Adidas shoes',),('Levice Jeans',),('adidas jersey',))

out=[]


Chats = (('Nike shoes have an offer',),('They are at a discount',),
     ('Nike shoes are the best',),('They have other offers as well',),
     ('They have introduced new shoes which are awesome',))
for i in Keywords:
    for j in i:
        for k in Chats:
            for l in k:
                if j in l:
                    out.append(j)
out1=tuple(out)
print(out1)

这会给你和你需要的一样的输出

给定的数据是tuple,因为它们来自DB。因此,您可能需要先更改数据(当然有不同的方法。)

Keywords =(('Nike shoes',),('Adidas shoes',),('Levice Jeans',),('adidas jersey',))

Chats = (('Nike shoes have an offer',),('They are at a discount',),
         ('Nike shoes are the best',),('They have other offers as well',),
         ('They have introduced new shoes which are awesome',))

# Make them lists because it's easy to use in your case
keywords = [keyword[0].lower() for keyword in Keywords]
chats = [chat[0].lower() for chat in Chats]

# Store all the common words into list3
list3 = []
for keyword in keywords:
    if any(keyword in chat for chat in chats):
        list3.append(keyword)

print(list3)
# ['nike shoes']

当前数据不需要keyword[0].lower()部分,但将所有文本转换为小写进行比较可能会有所帮助

相关问题 更多 >