gpt4 book ai didi

python - 用户输入中使用了数组 A 和数组 B 中的多少个单词?

转载 作者:行者123 更新时间:2023-12-04 00:18:04 24 4
gpt4 key购买 nike

这是一个我需要帮助的程序

   A = ["having", "had", "is"]
B = ["will", "would", "should"]

sentence = input("Enter a sentence") #E.g. 'I will be having it in the future'

if A in sentence:
...

elif B in sentence:
...

这里我需要知道句子中使用了数组 A 和数组 B 中的多少个单词。

这里的输出应该是:
句子中有1个A词和1个B词

你能帮帮我吗?

最佳答案

一个相当有效的方法是将 AB 和句子放入集合中并找到它们的交集的长度。例如:

A = set(["having", "had", "is"])
B = set(["will", "would", "should"])

sentence = 'I will be having it in the future'
S = set(sentence.split())

A_words = A.intersection(S)
B_words = B.intersection(S)

print(f'There is {len(A_words)} word from A and {len(B_words)} word from B in the sentence')

输出:

There is 1 word from A and 1 word from B in the sentence

关于python - 用户输入中使用了数组 A 和数组 B 中的多少个单词?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62607497/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com