如何统计字符串中某个字符出现的次数?
例如,在字符串“Mary had a little lamb”中,“a”出现了4次。
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()
如果您正在寻找文本中所有字符的计数,则这是已接受答案的扩展。
# 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}
str
并将其设置为字符串? str
是核心 Python 中的标准模块。请检查 python 中的 builtins
并永远不要将它们与其他值一起覆盖。问题要求计算每个字符的出现次数。你的答案在哪里,可以计算并以适当的数据结构(List[tuple]
或 Dict[str, int]
)呈现?同时,您使用大写字母作为变量名。请只使用蛇形命名法,并且除非它们用于表示常量,否则不要使用大写字母的变量名。 - CypherX引用这个用户的评论:
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中实现的,而你通常也会导入它。你也可以计算一个单词列表中唯一单词的数量。
在我看来,不需要更多 - 你可以添加上限或下限方法
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 Mortensendef count_letter(text):
result = {}
for letter in text:
if letter not in result:
result[letter] = 0
result[letter] += 1
return result
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))