首页 文章

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

提问于
浏览
775

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

例如计算 'a' 中出现 'a' 的次数

17 回答

  • 46

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

    from collections import Counter
    str = "Mary had a little lamb"
    counter = Counter(str)
    print counter['a']
    
  • 123
    myString.count('a');
    

    更多信息here

  • 23
    "aabc".count("a")
    
  • 86

    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' .

  • 0

    正则表达式可能?

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

    使用计数:

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

    x = 2 .

  • 0

    这将为您提供字符串中每个字符的出现 . 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")
    
  • 9
    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))
    
  • 14

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

    def count_letter_in_str(string,letter):
        return string.count(letter)
    
  • -3

    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
    
  • 8

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

    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}
    
  • 1096

    你可以使用count()

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

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

    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非常长或代码在深层循环内时才会出现问题 .

  • 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()
    
  • 2
    a = 'have a nice day'
    symbol = 'abcdefghijklmnopqrstuvwxyz'
    for key in symbol:
        print key, a.count(key)
    
  • 2

    str.count(sub [,start [,end]])返回[start,end]范围内substring sub的非重叠出现次数 . 可选参数start和end被解释为切片表示法 .

    >>> sentence = 'Mary had a little lamb'
    >>> sentence.count('a')
    4
    
  • -1
    str = "count a character occurance"
    
    List = list(str)
    print (List)
    Uniq = set(List)
    print (Uniq)
    
    for key in Uniq:
        print (key, str.count(key))
    

相关问题