我想检查某些单词是否出现在输入文本中,如果出现,有多少次
这些是我的投入:
keywords = ["apple", "banana", "orange", "lemon"]
text = "This apple is very tasty but the banana is not delicious at all."
现在我想计算一下关键字列表中的一个单词在输入文本中出现的次数
因此,对于本例,输出应该类似:
“我找到了两个字
这就是我目前得到的结果,但在这种情况下,它输出的是0,而不是2
text = "This apple is very tasty but the banana is not delicious at all."
keywords = ["apple", "banana", "orange", "lemon"]
def dictionary_score(text):
wordcount=0
for line in text:
line = line.strip()
line = line.lower()
words = line.split(" ")
for word in words:
if keywords in words:
wordcount += 1
print(f"I found {wordcount} words")
正确计数的问题在哪里
text
是一个字符串,并且for line in text
对该字符串的字符进行迭代。可替换为for line in text.splitlines():
应该是
if word in keywords:
而不是if keywords in words:
输出:
I found 2 words
问题在于
if keywords in words:
。它检查keywords
列表的全部是否在words
列表中您可能想检查每个
word
是否在keywords
列表中:您的代码有几个错误:
for line in text:
在获取字符串中的字符后,对字符串中的每个字符进行迭代,降低并拆分它if keywords in words:
这里您正在检查关键字列表是否在单词列表中,因为前面的解释是空的这里是固定代码:
输出:
I found 2 words
相关问题 更多 >
编程相关推荐