25

我正在尝试查找字符串中某个单词的出现次数。

word = "dog"
str1 = "the dogs barked"

我使用以下方法来计算出现次数:

count = str1.count(word)

问题是我想要一个完全匹配的。所以这句话的计数是0。这可能吗?

4

14 回答 14

43

如果您要提高效率:

import re
count = sum(1 for _ in re.finditer(r'\b%s\b' % re.escape(word), input_string))

这不需要创建任何中间列表(与 不同split()),因此可以有效地处理大input_string值。

它还具有正确使用标点符号的好处-它将正确地返回1为短语的计数"Mike saw a dog."(而无参数则split()不会)。它使用\b正则表达式标志,它匹配单词边界(\waka[a-zA-Z0-9_]和其他任何东西之间的转换)。

如果您需要担心 ASCII 字符集以外的语言,您可能需要调整正则表达式以正确匹配这些语言中的非单词字符,但对于许多应用程序来说,这将过于复杂,并且在许多其他情况下设置 unicode 和/ 或正则表达式的语言环境标志就足够了。

于 2013-06-24T06:09:29.967 回答
16

您可以使用str.split()将句子转换为单词列表:

a = 'the dogs barked'.split()

这将创建列表:

['the', 'dogs', 'barked']

然后,您可以使用以下方法计算确切出现的次数list.count()

a.count('dog')  # 0
a.count('dogs') # 1

如果它需要使用标点符号,您可以使用正则表达式。例如:

import re
a = re.split(r'\W', 'the dogs barked.')
a.count('dogs') # 1
于 2013-06-24T06:10:28.620 回答
5

使用列表推导:

>>> word = "dog"
>>> str1 = "the dogs barked"
>>> sum(i == word for word in str1.split())
0

>>> word = 'dog'
>>> str1 = 'the dog barked'
>>> sum(i == word for word in str1.split())
1

split()返回一个句子中所有单词的列表。然后我们使用列表推导来计算单词在句子中出现的次数。

于 2013-06-24T06:09:12.340 回答
4
import re

word = "dog"
str = "the dogs barked"
print len(re.findall(word, str))
于 2013-06-24T09:58:30.597 回答
3

您需要将句子拆分为单词。对于你的例子,你可以做到这一点

words = str1.split()

但是对于真正的单词使用,您需要更高级的东西来处理标点符号。对于大多数西方语言,您可以在做之前用空格替换所有标点符号str1.split()

这在简单的情况下也适用于英语,但请注意“I'm”将被拆分为两个词:“I”和“m”,实际上它应该被拆分为“I”和“am”。但这对于这个应用程序来说可能是多余的。

对于其他情况,例如亚洲语言或英语在现实世界中的实际使用,您可能希望使用一个为您进行分词的库。

然后你有一个单词列表,你可以做

count = words.count(word)
于 2013-06-24T06:12:10.290 回答
1

如果你不需要RegularExpression那么你可以做这个巧妙的技巧

word = " is " #Add space at trailing and leading sides.
input_string = "This is some random text and this is str which is mutable"
print("Word count : ",input_string.count(word))
Output -- Word count :  3
于 2019-05-18T19:21:22.430 回答
1
    #counting the number of words in the text
def count_word(text,word):
    """
    Function that takes the text and split it into word
    and counts the number of occurence of that word
    input: text and word
    output: number of times the word appears
    """
    answer = text.split(" ")
    count = 0
    for occurence in answer:
        if word == occurence:
            count = count + 1
    return count

sentence = "To be a programmer you need to have a sharp thinking brain"
word_count = "a"
print(sentence.split(" "))
print(count_word(sentence,word_count))

#output
>>> %Run test.py
['To', 'be', 'a', 'programmer', 'you', 'need', 'to', 'have', 'a', 'sharp', 'thinking', 'brain']
2
>>> 

创建接受两个输入的函数,即文本和单词的句子。将句子的文本拆分成列表中的单词段,然后检查要统计的单词是否存在于被分割的单词中,并将出现次数作为函数的返回。

于 2018-08-02T10:37:48.950 回答
0

如果您想找到特定单词在 sting 中的确切出现次数并且不想使用任何计数功能,则可以使用以下方法。

text = input("Please enter the statement you want to check: ")
word = input("Please enter the word you want to check in the statement: ")

# n is the starting point to find the word, and it's 0 cause you want to start from the very beginning of the string.
n = 0

# position_word is the starting Index of the word in the string
position_word = 0
num_occurrence = 0

if word.upper() in text.upper():
    while position_word != -1:
        position_word = text.upper().find(word.upper(), n, len(text))

        # increasing the value of the stating point for search to find the next word
        n = (position_word + 1)

        # statement.find("word", start, end) returns -1 if the word is not present in the given statement. 
        if position_word != -1:
            num_occurrence += 1

    print (f"{word.title()} is present {num_occurrence} times in the provided statement.")

else:
    print (f"{word.title()} is not present in the provided statement.")
于 2019-11-27T08:07:57.907 回答
0

我刚刚开始学习一般的编码,我不知道任何这样的库。

s = "the dogs barked"
value = 0
x = 0
y=3
for alphabet in s:
    if (s[x:y]) == "dog":
        value = value+1
    x+=1
    y+=1
print ("number of dog in the sentence is : ", value)  
于 2021-06-24T16:51:02.237 回答
0

这将是我在评论的帮助下的解决方案:

word = str(input("type the french word chiens in english:"))
str1 = "dogs"
times = int(str1.count(word))
if times >= 1:
    print ("dogs is correct")
else:
    print ("your wrong")
于 2017-07-15T19:51:46.100 回答
0

让我们考虑这个例子s = "suvotisuvojitsuvo"。如果你想计算不同的计数“suvo”和“suvojit”,那么你使用count()方法......计算不同的ie)你不计算suvojit到suvo..只计算孤独的“suvo”。

suvocount = s.count("suvo") // #output: 3
suvojitcount = s.count("suvojit") //# output : 1

然后找到你必须从 suvojit 计数中否定的孤独 suvo 计数。

lonelysuvo = suvocount - suvojicount //# output: 3-1 -> 2
于 2017-03-29T01:10:43.673 回答
0

下面是一个简单的例子,我们可以用新词替换所需的词,也可以替换所需的出现次数:

import string

def censor(text, word):<br>
    newString = text.replace(word,"+" * len(word),text.count(word))
    print newString

print censor("hey hey hey","hey")

输出将是:+++ +++ +++

函数中的第一个参数是 search_string。第二个是 new_string,它将替换您的 search_string。第三个也是最后一个是出现次数。

于 2015-08-05T06:34:53.663 回答
0

另一种方法是通过标记字符串(分解成单词)

使用Python 标准库的集合模块中的计数器

from collections import Counter 

str1 = "the dogs barked"
stringTokenDict = { key : value for key, value in Counter(str1.split()).items() } 

print(stringTokenDict['dogs']) 
#This dictionary contains all words & their respective count 
于 2021-12-05T08:07:12.827 回答
0

这是一个使用 split 函数的简单 python 程序

str = 'apple mango apple orange orange apple guava orange'
print("\n My string ==> "+ str +"\n")
str = str.split()
str2=[]

for i in str:
     if i not in str2:
         str2.append(i)
         print( i,str.count(i))
于 2020-09-10T10:34:41.797 回答