【问题标题】:How do I calculate the number of times a word occurs in a sentence?如何计算一个单词在句子中出现的次数?
【发布时间】:2012-01-06 12:37:14
【问题描述】:

所以我已经学习 Python 几个月了,我想知道如何编写一个函数来计算一个单词在一个句子中出现的次数。如果有人可以给我一个逐步的方法,我将不胜感激。

【问题讨论】:

标签: python string function


【解决方案1】:

快速回答:

def count_occurrences(word, sentence):
    return sentence.lower().split().count(word)

'some string.split() 会将空格(空格、制表符和换行符)上的字符串拆分成一个单词列表。然后['some', 'string'].count(item) 返回item 在列表中出现的次数。

这不涉及删除标点符号。你可以使用string.maketransstr.translate 来做到这一点。

# Make collection of chars to keep (don't translate them)
import string
keep = string.lowercase + string.digits + string.whitespace
table = string.maketrans(keep, keep)
delete = ''.join(set(string.printable) - set(keep))

def count_occurrences(word, sentence):
    return sentence.lower().translate(table, delete).split().count(word)

这里的关键是我们构造了字符串delete,使它包含除字母、数字和空格之外的所有ascii 字符。然后str.translate 在这种情况下采用不更改字符串的转换表,但也需要删除一串字符。

【讨论】:

  • string.translate 在技术上位于文档的已弃用部分,所以我会小心使用该功能作为习惯。
  • 你是对的 - 我将文本更改为引用 str.translate,这是这样做的幸运方式。
【解决方案2】:

wilberforce 有快速、正确的答案,我会给出冗长的“如何得出这个结论”的答案。

首先,这里有一些帮助您入门的工具,以及您需要问自己的一些问题。

您需要阅读 python 文档中关于 Sequence Types 的部分,因为它是解决此问题的最佳朋友。认真的,读一读。读完之后,你应该有一些想法。例如,您可以获取一个长字符串并使用 split() 函数将其分解。明确地说:

mystring = "This sentence is a simple sentence."
result = mystring.split()
print result
print "The total number of words is: "  + str(len(result))
print "The word 'sentence' occurs: " + str(result.count("sentence"))

获取输入字符串并将其拆分为任何空格,然后会给您:

["This", "sentence", "is", "a", "simple", "sentence."]
The total number of words is 6
The word 'sentence' occurs: 1

现在请注意,句号仍然位于第二个“句子”的末尾。这是一个问题,因为“句子”与“句子”不同。如果您要查看列表并计算单词,则需要确保字符串相同。您可能需要找到并删除一些标点符号。

对此的一种天真的方法可能是:

no_period_string = mystring.replace(".", " ")
print no_period_string

给我一​​个没有句号的句子:

"This sentence is a simple sentence"

您还需要确定您的输入是一个句子,还是一段文本。如果您的输入中有很多句子,您可能想找到一种方法将它们分解成单独的句子,并找到句点(或问号、感叹号或其他以句号结尾的标点符号)句子)。一旦您找出字符串中“句子终止符”的位置,您就可以在该点拆分字符串,或类似的东西。

您应该自己尝试一下 - 希望我已经提供了足够的提示,让您查看文档中的一些特定功能。

【讨论】:

  • 回答“这个句子中有多少个词?”,而不是“这个词在这个句子中出现了多少次?”。 :)
  • 天哪。阅读失败。修复。
【解决方案3】:

最简单的方法:

def count_occurrences(word, sentence):
    return sentence.count(word)

【讨论】:

    【解决方案4】:
    text=input("Enter your sentence:")
    print("'the' appears", text.count("the"),"times")
    

    最简单的方法

    【讨论】:

      【解决方案5】:

      你可以这样做:

      def countWord(word):
      
          numWord = 0
          for i in range(1, len(word)-1):
              if word[i-1:i+3] == 'word':
                  numWord += 1
          print 'Number of times "word" occurs is:', numWord
      

      然后调用字符串:

      countWord('wordetcetcetcetcetcetcetcword')
      

      将返回:Number of times "word" occurs is: 2

      【讨论】:

        【解决方案6】:

        def check_Search_WordCount(mySearchStr, mySentence):

        len_mySentence = len(mySentence)
        len_Sentence_without_Find_Word = len(mySentence.replace(mySearchStr,""))
        len_Remaining_Sentence = len_mySentence - len_Sentence_without_Find_Word
        count = len_Remaining_Sentence/len(mySearchStr)
        return (int(count))
        

        【讨论】:

        • 只贴代码不解释对提问的人帮助不大。
        • 嗨,这很简单... Step1) 获取字符串的总长度 - "len_mySentence" Step2) 获取不带搜索词的字符串长度 - "len_Sentence_without_Find_Word" Step3) 两个长度的减法 - "len_Remaining_Sentence" Step4 ) 最后除以 len_Remaining_Sentence 与 Search Word length........
        【解决方案7】:

        我假设你只知道 python 字符串和 for 循环。

        def count_occurences(s,word):
        
            count = 0
            for i in range(len(s)): 
                if s[i:i+len(word)] == word:
                    count += 1    
            return count
        
        mystring = "This sentence is a simple sentence."
        myword = "sentence"
        print(count_occurences(mystring,myword))
        

        解释: s[i:i+len(word)]: 对字符串 s 进行切片,提取一个与单词长度相同的单词(参数) count += 1 : 匹配时增加计数器。

        【讨论】:

        • 这太复杂了。
        【解决方案8】:

        使用 count() 方法的问题是,例如,当存在重叠时,它并不总是给出正确的出现次数

        print('banana'.count('ana'))
        

        输出

        1
        

        但是“ana”在“banana”中出现了两次

        为了解决这个问题,我使用了

        def total_occurrence(string,word):
            count = 0
            tempsting = string
            while(word in tempsting):
                count +=1
                tempsting = tempsting[tempsting.index(word)+1:]
            return count
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2016-01-09
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多