如何在文本中找到特定的单词并使用python计算它们?

2024-04-20 02:48:44 发布

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

我想检查某些单词是否出现在输入文本中,如果出现,有多少次

这些是我的投入:

  • 单词列表: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") 

正确计数的问题在哪里


Tags: textin文本apple列表islinethis
3条回答
  1. text是一个字符串,并且for line in text对该字符串的字符进行迭代。可替换为for line in text.splitlines():

  2. 应该是if word in keywords:而不是if keywords in words:

    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.splitlines():
            print(line)
            line = line.strip()
            line = line.lower()
            words = line.split(" ")
            for word in words:
                if word in keywords:
                    wordcount += 1
        print(f"I found {wordcount} words") 
    
    dictionary_score(text)```
    
    
    

输出:I found 2 words

问题在于if keywords in words:。它检查keywords列表的全部是否在words列表中

您可能想检查每个word是否在keywords列表中:

if word in keywords:

您的代码有几个错误:

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: #Iterate over each string character
        line = line.strip()
        line = line.lower()
        words = line.split(" ") #Here the list will be empty, because you are operating on a character.
        for word in words: #You are iterating over a empty list
            if keywords in words: #Checking if the list keywords is in words(that is empty)
                wordcount += 1
print(f"I found {wordcount} words") 
  • for line in text:在获取字符串中的字符后,对字符串中的每个字符进行迭代,降低并拆分它

  • if keywords in words:这里您正在检查关键字列表是否在单词列表中,因为前面的解释是空的

这里是固定代码:

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
    words = text.strip().lower().split(" ") #split the string, after stripping and lowering it
    for word in words: # Iterate over the words
        if word in keywords: # If the word is in the keywords list increment the counter
            wordcount += 1
    print(f"I found {wordcount} words") 

dictionary_score(text)

输出:I found 2 words

相关问题 更多 >