简体   繁体   English

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

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

I'm trying to count the occurrence of each character for any given string input, the occurrences must be output in ascending order( includes numbers and exclamation marks) I have this for my code so far, i am aware of the Counter function, but it does not output the answer in the format I'd like it to, and I do not know how to format Counter. 我正在尝试为任何给定的字符串输入计算每个字符的出现次数,出现的次数必须以升序输出(包括数字和感叹号)。到目前为止,我的代码已经知道了这一点,我知道Counter函数,但是它不会以我想要的格式输出答案,并且我不知道如何格式化Counter。 Instead I'm trying to find away to use the count() to count each character. 相反,我试图找出使用count()来计数每个字符的方法。 I've also seen the dictionary function , but I'd be hoping that there is a easier way to do it with 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)

Just call .most_common and reverse the output with reversed to get the output from least to most common: 只需调用.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 objects provide a most_common() method that returns a list of tuples in decreasing frequency. collections.Counter对象提供了一个most_common()方法,该方法以递减的频率返回元组列表。 So, if you want it in ascending frequency, reverse the list: 因此,如果您希望以递增的频率使用它,请反转列表:

from collections import Counter

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

Demo run 演示运行

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

Your best bet is to use Counter (which does work on a string) and then sort on it's output. 最好的选择是使用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)

If you just want to format the Counter output differently: 如果只想以不同的方式格式化Counter输出:

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

Another way to avoid using Counter. 避免使用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])

Output: 输出:

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.

One way to do this would be by removing instances of your sub string and looking at the length... 一种方法是删除子字符串的实例并查看其长度...

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

alternatively you could use re or regular expressions, 或者,您可以使用re或正则表达式,

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

finally you could count them manually, 最终您可以手动计算它们,

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

Test any of the three with... 用...测试三个

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

Now that you can count any given character you can iterate through your string's unique characters and apply a counter for each unique character you find. 现在您可以计数任何给定的字符,可以遍历字符串的唯一字符,并对找到的每个唯一字符应用计数器。 Then sort and print the result. 然后排序并打印结果。

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)

You could use the list function to break the words apart`from collections 您可以使用列表功能将单词与集合分开

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