final_list = [ ]
words = ['good', 'bad', 'excellent','delivery', 'quality','upset','better','poor','refund','fake','cheat','quick','long','scam','cheaper','aluminium']
def func(words, list1):
cnt = 0
final_list = [ ]
for i in list1:
no_of_words = len(i.split())
# print(no_of_words)
# print(i)
if no_of_words>2:
for word in i.split(): # Only printing the records where occurence of words >2
# print(word)
if word in words:
cnt+=1
if cnt>2:
final_list.append(i)
cnt = 0
return final_list
final_list = func(words, )
print( *final_list, sep = ' \n\n')上面给定的代码打印列'list1‘的行元素,其中行元素包含列表' words’中的单词,其中单词> 2。
就像。我是个很好的送货人,但有时顾客还是会骗我的。
考虑这是行元素之一。如果给出这一行,它将被打印,因为(words>2)条件满足i,e好,交付,欺骗在我的列表'words‘中。
但是我想修改这个函数。除了上面的条件,我们还想检查行元素中的单个words>2
比如..。我是一个好的送货员,我对人做好事,我不欺骗任何人,但人们对我不好,经常欺骗我。
上面给出的例子不会被打印出来。因为:
words>2)
请帮我修改一下我的功能。
发布于 2022-09-23 07:07:48
可以将列表中的每个元素拆分,并与列表单词匹配,并检查元素的重复项是否大于2。
from collections import Counter
list1 = ['good good delivery good cheat delivery cheat delivery cheat', 'good
cheat', 'fake good good fake']
words = ['good', 'bad', 'excellent', 'delivery', 'quality', 'upset', 'better',
'poor', 'refund', 'fake', 'cheat','quick', 'long', 'scam', 'cheaper', 'aluminium']
repeated_words = []
for word in list1:
data = word.split()
match_data = [i for i in data if any((j in i) for j in words)]
count_data = [k for k, v in Counter(match_data).items() if v > 2]
if count_data:
repeated_words.append(word)
print(repeated_words)
>>>> ['good good delivery good cheat delivery cheat delivery cheat']https://stackoverflow.com/questions/73823191
复制相似问题