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

时间:2017-03-01 16:13:47

标签: 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')

我尝试了各种各样的事情,但发现了错误,例如"列表值应该是整数,而不是元组"

2 个答案:

答案 0 :(得分:0)

给定数据是元组,因为它们来自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()部分,但将所有文本转换为小写进行比较可能会有所帮助。

答案 1 :(得分:0)

你可以这样做:

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)

这将为您提供所需的相同输出。