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

2024-10-06 13:26:29 发布

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

这是一个我需要帮助的项目

   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中的多少个单词

此处的输出应为:
有一个单词来自A&;句子中B的1个单词

你能帮帮我吗


Tags: 项目ininputis数组be单词will
3条回答

这应该行得通

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

   sentence = input("Enter a sentence") #E.g. 'I will be having it in the future'
   words_in_sentence = sentence.split()
   # words_in_sentence = np.unique(words_in_sentence) # If you only want unique words
   n_A = len([word for word in words_in_sentence if word in A])
   n_B = len([word for word in words_in_sentence if word in B])

如果要计算每个列表中的数字,则此操作应有效:

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

sentence = input("Enter a sentence")
        
        
sentence_split = set(sentence.split())

nbr_words_A = 0
nbr_words_B = 0
for el in sentence_split:
    if el in A:
        nbr_words_A += 1
    if el in B:
        nbr_words_B += 1



print(f"There are {nbr_words_A} words from list A and {nbr_words_B} words from list B in the sentence")

一种相当有效的方法是将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

相关问题 更多 >