简体   繁体   English

如何比较Python中两个字符串列表中的特定单词数

[英]How to compare specific number of words among two lists of strings in Python

I need to write a script that takes two sentences as input and verifies if they contains exactly four words that are equal.我需要编写一个脚本,将两个句子作为输入并验证它们是否恰好包含四个相等的单词。 My code follow doesn't work as I have limited knowledge and I really value your knowledge!我的代码遵循不起作用,因为我的知识有限,我真的很重视你的知识!

I want to test if there are four distinct words in common.我想测试是否有四个不同的词是共同的。

input1 = "The winter season is cold and wet but snow is cool".split()

input2 = "The summer season is hot and humid but sun is shining".split()


count = 0
i = 1
input3 = []
while i == 4:
    for i in range(len(input1)):
        for j in range(len(input2)):
            if i in j:
                if j in i:
                    input3.append(i and j)
                    count += 1

Perhaps a nested for loop would work.也许嵌套的 for 循环会起作用。 Try this:试试这个:

input1 = "The winter season is cold and wet but snow is cool".split()
input2 = "The summer season is hot and humid but sun is shining".split()

input3 = []

for i in input1:
    for x in input2:
        if i == x:
            input3.append(i)

input3 = list(dict.fromkeys(input3)) #This removes duplicates from the list. Delete it if you want duplicates
if len(input3) == 4:
    print("Contains 4 Words")
    
print(input3)

set s are great for this. set非常适合这个。 No need for writing loops:无需编写循环:

input1 = "The winter season is cold and wet but snow is cool"
input2 = "The summer season is hot and humid but sun is shining"

distinct_words = set.intersection(*map(set, map(str.split, (input1, input2))))

print(len(distinct_words))

5

You could always just use the intersection operator as well:您也可以始终只使用交集运算符:

len(set(input1.split()) & set(input2.split()))

5

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM