问题:计算字符串中字符的出现次数

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

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

What’s the simplest way to count the number of occurrences of a character in a string?

e.g. count the number of times 'a' appears in 'Mary had a little lamb'


回答 0

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

返回sub范围中的子字符串不重叠的次数[start, end]。可选参数startend并按片表示法解释。

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

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

Return the number of non-overlapping occurrences of substring sub in the range [start, end]. Optional arguments start and end are interpreted as in slice notation.

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

回答 1

您可以使用count()

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

You can use count() :

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

回答 2

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

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

As other answers said, using the string method count() is probably the simplest, but if you’re doing this frequently, check out collections.Counter:

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

回答 3

正则表达式可能吗?

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

Regular expressions maybe?

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

回答 4

myString.count('a');

更多信息在这里

myString.count('a');

more info here


回答 5

Python-3.x:

"aabc".count("a")

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

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

Python-3.x:

"aabc".count("a")

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

Return the number of non-overlapping occurrences of substring sub in the range [start, end]. Optional arguments start and end are interpreted as in slice notation.


回答 6

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

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

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

str.count(a) is the best solution to count a single character in a string. But if you need to count more characters you would have to read the whole string as many times as characters you want to count.

A better approach for this job would be:

from collections import defaultdict

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

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

So you’ll have a dict that returns the number of occurrences of every letter in the string and 0 if it isn’t present.

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

For a case insensitive counter you could override the mutator and accessor methods by subclassing defaultdict (base class’ ones are read-only):

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

回答 7

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

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

check_freq("abbabcbdbabdbdbabababcbcbab")
{'a': 7, 'b': 14, 'c': 3, 'd': 3}

This easy and straight forward function might help:

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

check_freq("abbabcbdbabdbdbabababcbcbab")
{'a': 7, 'b': 14, 'c': 3, 'd': 3}

回答 8

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

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非常长或代码处于深循环内时才可能是一个问题。

Regular expressions are very useful if you want case-insensitivity (and of course all the power of regex).

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

Be aware that the regex version takes on the order of ten times as long to run, which will likely be an issue only if my_string is tremendously long, or the code is inside a deep loop.


回答 9

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

回答 10

str = "count a character occurance"

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

for key in Uniq:
    print (key, str.count(key))
str = "count a character occurance"

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

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

回答 11

另一种方式来获得所有的字符数不使用Counter()count和正则表达式

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)

An alternative way to get all the character counts without using Counter(), count and 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)

回答 12

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'在这种特殊情况下)时才起作用。

count is definitely the most concise and efficient way of counting the occurrence of a character in a string but I tried to come up with a solution using lambda, something like this :

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

This will result in :

4

Also, there is one more advantage to this is if the sentence is a list of sub-strings containing same characters as above, then also this gives the correct result because of the use of in. Have a look :

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

This also results in :

4

But Of-course this will work only when checking occurrence of single character such as 'a' in this particular case.


回答 13

“不使用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()

“Without using count to find you want character in string” method.

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

回答 14

我是熊猫图书馆的粉丝,尤其是value_counts()方法。您可以使用它来计算字符串中每个字符的出现:

>>> import pandas as pd
>>> phrase = "I love the pandas library and its `value_counts()` method"
>>> pd.Series(list(phrase)).value_counts()
     8
a    5
e    4
t    4
o    3
n    3
s    3
d    3
l    3
u    2
i    2
r    2
v    2
`    2
h    2
p    1
b    1
I    1
m    1
(    1
y    1
_    1
)    1
c    1
dtype: int64

I am a fan of the pandas library, in particular the value_counts() method. You could use it to count the occurrence of each character in your string:

>>> import pandas as pd
>>> phrase = "I love the pandas library and its `value_counts()` method"
>>> pd.Series(list(phrase)).value_counts()
     8
a    5
e    4
t    4
o    3
n    3
s    3
d    3
l    3
u    2
i    2
r    2
v    2
`    2
h    2
p    1
b    1
I    1
m    1
(    1
y    1
_    1
)    1
c    1
dtype: int64

回答 15

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

回答 16

Python 3

有两种方法可以实现此目的:

1)内置函数count()

sentence = 'Mary had a little lamb'
print(sentence.count('a'))`

2)不使用功能

sentence = 'Mary had a little lamb'    
count = 0

for i in sentence:
    if i == "a":
        count = count + 1

print(count)

Python 3

Ther are two ways to achieve this:

1) With built-in function count()

sentence = 'Mary had a little lamb'
print(sentence.count('a'))`

2) Without using a function

sentence = 'Mary had a little lamb'    
count = 0

for i in sentence:
    if i == "a":
        count = count + 1

print(count)

回答 17

仅此恕我直言-您可以添加上限或下限方法

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

No more than this IMHO – you can add the upper or lower methods

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

声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。