[英]How many words from the array A and array B are used in the user input?
This is a program where I need some help这是一个我需要帮助的程序
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:
...
Here I need to know how many words from the array A and array B are used in sentence.在这里,我需要知道在句子中使用了数组 A 和数组 B 中的多少单词。
The output here should be:这里的output应该是:
There is 1 word from A & 1 word from B in the sentence句子中有1个来自A的单词和1个来自B的单词
Can you help me out please?你能帮帮我吗?
A reasonably efficient way to do this is to make A
, B
and the sentence into sets and find the lengths of their intersections.一种合理有效的方法是将
A
、 B
和句子组成集合并找到它们的交叉点的长度。 For example:例如:
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')
Output: Output:
There is 1 word from A and 1 word from B in the sentence
This should work if you want to count the number present in each list:如果您想计算每个列表中存在的数字,这应该有效:
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")
This should work这应该工作
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])
You can follow this it will work.你可以按照这个它会工作。 But remember there can be a very short way to do this.
但请记住,可能有一种非常短的方法可以做到这一点。
A = ["having", "had", "is"]
B = ["will", "would", "should"]
sentence = input("Enter a sentence:") #E.g. 'I will be having it in the future'
a=0
for i in range(len(A)):
if A[i] in sentence:
a=a+1
b=0
for i in range(len(B)):
if B[i] in sentence:
b=b+1
print("There is {} word from A & {} word from B in the sentence".format(a,b))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.