简体   繁体   English

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

[英]Count number of occurrences of a character in a string

I'm just getting into Python and I'm building a program that analyzes a group of words and returns how many times each letter appears in the text. 我刚刚进入Python,我正在构建一个分析一组单词的程序,并返回每个字母出现在文本中的次数。 ie 'A:10, B:3, C:5...etc'. 即'A:10,B:3,C:5 ......等'。 So far it's working perfectly except that i am looking for a way to condense the code so i'm not writing out each part of the program 26 times. 到目前为止它工作得很好,除了我正在寻找一种方法来压缩代码,所以我不会写出程序的每个部分26次。 Here's what I mean.. 这就是我的意思..

print("Enter text to be analyzed: ")
message = input()

A = 0
b = 0
c = 0
...etc

for letter in message:

    if letter == "a":
        a += 1
    if letter == "b":
        b += 1
    if letter == "c":
        c += 1
    ...etc

print("A:", a, "B:", b, "C:", c...etc)

There are many ways to do this. 有很多方法可以做到这一点。 Most use a dictionary ( dict ). 大多数人使用字典( dict )。 For example, 例如,

count = {}
for letter in message:
    if letter in count:  # saw this letter before
        count[letter] += 1
    else:   # first time we've seen this - make its first dict entry
        count[letter] = 1

There are shorter ways to write it, which I'm sure others will point out, but study this way first until you understand it. 有更短的方式来编写它,我相信其他人会指出,但是先研究这种方式,直到你理解它为止。 This sticks to very simple operations. 这坚持非常简单的操作。

At the end, you can display it via (for example): 最后,您可以通过(例如)显示它:

for letter in sorted(count):
    print(letter, count[letter])

Again, there are shorter ways to do this, but this way sticks to very basic operations. 同样,有更短的方法可以做到这一点,但这种方式坚持非常基本的操作。

You can use Counter but @TimPeters is probably right and it is better to stick with the basics. 你可以使用Counter,但@TimPeters可能是正确的,最好坚持使用基础知识。

from collections import Counter

c = Counter([letter for letter in message if letter.isalpha()])
for k, v in sorted(c.items()):
    print('{0}: {1}'.format(k, v))

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

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