(Python)如何计算单词中的字母数?

2024-10-01 15:40:00 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图创建一个程序,如果你输入一个单词,它会打印出这个单词的每个字母,以及这个字母在这个单词中出现的次数。在

当我输入“aaaarggh”时,输出应该是“a4r1g2h1”。在

def compressed (word):
    count = 0
    index = 0
    while index < len(word):
        letter = word[index]
        for letter in word:
            index = index + 1
            count = count + 1
            print(letter, count)
        break

print("Enter a word:")
word = input()
compressed(word)

到目前为止,它只打印出单词中的每个字母和位置。 感谢任何帮助,谢谢!在

(不使用dict方法)


Tags: 程序indexlendefcount字母单词次数
3条回答

试试这个,你可以用计数器它会返回dict类型

from collections import Counter
print(Counter("aaaarggh"))

只需键入(对于Python 2.7+):

import collections
dict(collections.Counter('aaaarggh'))

拥有:

^{pr2}$
a="aaaarggh"
d={}
for char in set(a):
    d[char]=a.count(char)
print(d)

输出

^{pr2}$

相关问题 更多 >

    热门问题