繁体   English   中英

如何计算字符串中字符的出现次数(列表)

[英]How to count number of occurrences of a chracter in a string (list)

我正在尝试为任何给定的字符串输入计算每个字符的出现次数,出现的次数必须以升序输出(包括数字和感叹号)。到目前为止,我的代码已经知道了这一点,我知道Counter函数,但是它不会以我想要的格式输出答案,并且我不知道如何格式化Counter。 相反,我试图找出使用count()来计数每个字符的方法。 我也看过字典函数,但是我希望有一个更简单的方法可以通过count()来完成它。

from collections import Counter

sentence=input("Enter a sentence b'y: ")
lowercase=sentence.lower()

list1=list(lowercase)
list1.sort()

length=len(list1)
list2=list1.count(list1)
print(list2)

p=Counter(list1)
print(p)

只需调用.most_common并使用reversed反转输出即可将输出从最小到最常见:

from collections import Counter

sentence= "foobar bar"
lowercase = sentence.lower()
for k, count in  reversed(Counter(lowercase).most_common()):
    print(k,count)

collections.Counter对象提供了一个most_common()方法,该方法以递减的频率返回元组列表。 因此,如果您希望以递增的频率使用它,请反转列表:

from collections import Counter

sentence = input("Enter a sentence: ")
c = Counter(sentence.lower())
result = reversed(c.most_common())
print(list(result))

演示运行

Enter a sentence: Here are 3 sentences. This is the first one. Here is the second. The end!
[('a', 1), ('!', 1), ('3', 1), ('f', 1), ('d', 2), ('o', 2), ('c', 2), ('.', 3), ('r', 4), ('i', 4), ('n', 5), ('t', 6), ('h', 6), ('s', 7), (' ', 14), ('e', 14)]

最好的选择是使用Counter (对字符串有效),然后对它的输出进行排序。

from collections import Counter
sentence = input("Enter a sentence b'y: ")
lowercase = sentence.lower()

# Counter will work on strings
p = Counter(lowercase)
count = Counter.items()
# count is now (more or less) equivalent to
#  [('a', 1), ('r', 1), ('b', 1), ('o', 2), ('f', 1)]

# And now you can run your sort
sorted_count = sorted(count)
# Which will sort by the letter. If you wanted to
#  sort by quantity, tell the sort to use the
#  second element of the tuple by setting key:

# sorted_count = sorted(count, key=lambda x:x[1])

for letter, count in sorted_count:
    # will cycle through in order of letters.
    #  format as you wish
    print(letter, count)

如果只想以不同的方式格式化Counter输出:

for key, value in Counter(list1).items():
    print('%s: %s' % (key, value))

避免使用Counter的另一种方法。

sentence = 'abc 11 222 a AAnn zzz?? !'
list1 = list(sentence.lower())
#If you want to remove the spaces.
#list1 = list(sentence.replace(" ", ""))

#Removing duplicate characters from the string  
sentence = ''.join(set(list1))
dict = {}
for char in sentence:
    dict[char] = list1.count(char)

for item in sorted(dict.items(), key=lambda x: x[1]):
    print 'Number of Occurences of %s is %d.' % (item[0], item[1])

输出:

Number of Occurences of c is 1.
Number of Occurences of b is 1.
Number of Occurences of ! is 1.
Number of Occurences of n is 2.
Number of Occurences of 1 is 2.
Number of Occurences of ? is 2.
Number of Occurences of 2 is 3.
Number of Occurences of z is 3.
Number of Occurences of a is 4.
Number of Occurences of   is 6.

一种方法是删除子字符串的实例并查看其长度...

def nofsub(s,ss):
    return((len(s)-len(s.replace(ss,"")))/len(ss))

或者,您可以使用re或正则表达式,

from re import *
def nofsub(s,ss):
    return(len(findall(compile(ss), s)))

最终您可以手动计算它们,

def nofsub(s,ss):
    return(len([k for n,k in enumerate(s) if s[n:n+len(ss)]==ss]))

用...测试三个

>>> nofsub("asdfasdfasdfasdfasdf",'asdf')
5

现在您可以计数任何给定的字符,可以遍历字符串的唯一字符,并对找到的每个唯一字符应用计数器。 然后排序并打印结果。

def countChars(s):
    s = s.lower()
    d = {}
    for k in set(s):
        d[k]=nofsub(s,k)
    for key, value in sorted(d.iteritems(), key=lambda (k,v): (v,k)):
        print "%s: %s" % (key, value)

您可以使用列表功能将单词与集合分开

from collections import Counter

sentence=raw_input("Enter a sentence b'y: ")
lowercase=sentence.lower()

list1=list(lowercase)
list(list1)

length=len(list1)
list2=list1.count(list1)
print(list2)

p=Counter(list1)
print(p)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM