在一个字符串中计算一个字符出现的次数。

1286

如何统计字符串中某个字符出现的次数?

例如,在字符串“Mary had a little lamb”中,“a”出现了4次。


为了交叉检查基于下面的最佳答案的结果,您还可以使用此工具。 - WJA
你可能会找到编码的最简单方法,但最终,无论我们使用循环还是内置的count()函数,时间复杂度仍然保持不变。 - Makarand
26个回答

1
“不使用count方法查找字符串中想要的字符”的方法。
import re

def count(s, ch):

   pass

def main():

   s = raw_input ("Enter strings what you like, for example, 'welcome': ")  

   ch = raw_input ("Enter you want count characters, but best result to find one character: " )

   print ( len (re.findall ( ch, s ) ) )

main()

10
为什么要使用空计数函数?为什么要使用main()函数?为什么到处都是丑陋的空格?这不是一个好的答案。 - bugmenot123

1

如果您正在寻找文本中所有字符的计数,则这是已接受答案的扩展。

# Objective: we will only count for non-empty characters

text = "count a character occurrence"
unique_letters = set(text)
result = dict((x, text.count(x)) for x in unique_letters if x.strip())

print(result)
# {'a': 3, 'c': 6, 'e': 3, 'u': 2, 'n': 2, 't': 2, 'r': 3, 'h': 1, 'o': 2}

Downvote。重复的问题已经在 https://dev59.com/7nM_5IYBdhLWcg3w9oIA#49385352 中回答,而不需要使用列表集合,您可以直接在字符串上使用set()来获取唯一字符。 - questionto42
这个回答有太多的警告!为什么要覆盖 str 并将其设置为字符串? str 是核心 Python 中的标准模块。请检查 python 中的 builtins 并永远不要将它们与其他值一起覆盖。问题要求计算每个字符的出现次数。你的答案在哪里,可以计算并以适当的数据结构(List[tuple]Dict[str, int])呈现?同时,您使用大写字母作为变量名。请只使用蛇形命名法,并且除非它们用于表示常量,否则不要使用大写字母的变量名。 - CypherX

0

引用这个用户的评论:

import numpy as np
sample = 'samplestring'
np.unique(list(sample), return_counts=True)

输出:

(array(['a', 'e', 'g', 'i', 'l', 'm', 'n', 'p', 'r', 's', 't'], dtype='<U1'),
 array([1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 1]))

检查 's'。您可以按以下方式过滤这个由两个数组组成的元组:

a[1][a[0]=='s']

顺便提一下:它的工作方式类似于collections包中的Counter(),只不过是在numpy中实现的,而你通常也会导入它。你也可以计算一个单词列表中唯一单词的数量。


-1

在我看来,不需要更多 - 你可以添加上限或下限方法

def count_letter_in_str(string,letter):
    return string.count(letter)

这可能导致"error CS1061: 'string' does not contain a definition for 'count' and no accessible extension method 'count' accepting a first argument of type 'string' could be found (are you missing a using directive or an assembly reference?)"。 - Peter Mortensen

-1
你可以使用循环和字典。
def count_letter(text):
    result = {}
    for letter in text:
        if letter not in result:
            result[letter] = 0
        result[letter] += 1
    return result

-2
spam = 'have a nice day'
var = 'd'


def count(spam, var):
    found = 0
    for key in spam:
        if key == var:
            found += 1
    return found
count(spam, var)
print 'count %s is: %s ' %(var, count(spam, var))

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接