计算字符串中字符的出现次数

问题描述 投票:854回答:18

计算字符串中字符出现次数的最简单方法是什么?

例如计算'a''Mary had a little lamb'出现的次数

python string count
18个回答
1238
投票

str.count(sub[, start[, end]])

返回sub范围内子字符串[start, end]的非重叠出现次数。可选参数startend被解释为切片表示法。

>>> sentence = 'Mary had a little lamb'
>>> sentence.count('a')
4

5
投票
a = 'have a nice day'
symbol = 'abcdefghijklmnopqrstuvwxyz'
for key in symbol:
    print key, a.count(key)

2
投票
str = "count a character occurance"

List = list(str)
print (List)
Uniq = set(List)
print (Uniq)

for key in Uniq:
    print (key, str.count(key))

2
投票

count绝对是计算字符串中字符出现次数最简洁有效的方法,但我尝试使用lambda提出一个解决方案,如下所示:

sentence = 'Mary had a little lamb'
sum(map(lambda x : 1 if 'a' in x else 0, sentence))

这将导致:

4

此外,还有一个优点是,如果句子是包含与上述相同字符的子字符串列表,那么由于使用了in,这也给出了正确的结果。看一看 :

sentence = ['M', 'ar', 'y', 'had', 'a', 'little', 'l', 'am', 'b']
sum(map(lambda x : 1 if 'a' in x else 0, sentence))

这也导致:

4

但是当然这只有在这种特殊情况下检查单个字符的出现时才有效,例如'a'


2
投票

不使用Counter()count和regex获得所有字符数的另一种方法

counts_dict = {}
for c in list(sentence):
  if c not in counts_dict:
    counts_dict[c] = 0
  counts_dict[c] += 1

for key, value in counts_dict.items():
    print(key, value)

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()

0
投票
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))

0
投票

只不过这个恕我直言 - 你可以添加上层或下层方法

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

-2
投票

使用计数:

string = "count the number of counts in string to count from."
x = string.count("count")

x = 3。


-4
投票

这将为您提供字符串中每个字符的出现。 O / P也是字符串格式:

def count_char(string1):
string2=""
lst=[]
lst1=[]
for i in string1:
    count=0
    if i not in lst:
        for j in string1:
            if i==j:
                count+=1
        lst1.append(i)
        lst1.append(count)
    lst.append(i)

string2=''.join(str(x) for x in lst1)
return string2 

print count_char("aabbacddaabbdsrchhdsdg")

139
投票

你可以使用count()

>>> 'Mary had a little lamb'.count('a')
4

99
投票

正如其他答案所说,使用字符串方法count()可能是最简单的,但如果你经常这样做,请查看collections.Counter

from collections import Counter
my_str = "Mary had a little lamb"
counter = Counter(my_str)
print counter['a']

48
投票

正则表达式可能?

import re
my_string = "Mary had a little lamb"
len(re.findall("a", my_string))

26
投票
myString.count('a');

更多信息here


15
投票
"aabc".count("a")

13
投票

str.count(a)是计算字符串中单个字符的最佳解决方案。但是如果你需要计算更多的字符,你必须读取整个字符串的次数与你想要计算的字符数一样多。

这项工作的更好方法是:

from collections import defaultdict

text = 'Mary had a little lamb'
chars = defaultdict(int)

for char in text:
    chars[char] += 1

因此,您将拥有一个dict,它返回字符串中每个字母的出现次数,如果不存在则返回0

>>>chars['a']
4
>>>chars['x']
0

对于不区分大小写的计数器,您可以通过继承defaultdict来覆盖mutator和accessor方法(基类'是只读的):

class CICounter(defaultdict):
    def __getitem__(self, k):
        return super().__getitem__(k.lower())

    def __setitem__(self, k, v):
        super().__setitem__(k.lower(), v)


chars = CICounter(int)

for char in text:
    chars[char] += 1

>>>chars['a']
4
>>>chars['M']
2
>>>chars['x']
0

9
投票

如果你想要不区分大小写(当然还有正则表达式的所有功能),正则表达式非常有用。

my_string = "Mary had a little lamb"
# simplest solution, using count, is case-sensitive
my_string.count("m")   # yields 1
import re
# case-sensitive with regex
len(re.findall("m", my_string))
# three ways to get case insensitivity - all yield 2
len(re.findall("(?i)m", my_string))
len(re.findall("m|M", my_string))
len(re.findall(re.compile("m",re.IGNORECASE), my_string))

请注意,正则表达式版本的运行时间大约为十倍,这可能仅在my_string非常长或代码在深层循环内时才会出现问题。


9
投票

这个简单直接的功能可能会有所帮助:

def check_freq(str):
    freq = {}
    for c in str:
       freq[c] = str.count(c)
    return freq

check_freq("abbabcbdbabdbdbabababcbcbab")
{'a': 7, 'b': 14, 'c': 3, 'd': 3}
© www.soinside.com 2019 - 2024. All rights reserved.