在一个字符串中计算字符出现的次数

4
我被要求计算用户输入的字符串中字母、空格和标点符号的出现次数。在输出中,字母应按它们在文本中出现的顺序排列,但不应出现两次,大小写字母应被视为一个字符。我目前的代码如下。
S = str(input("Enter a string: "))
S = S.lower()
alpha = "abcdefghijklmnopqrstuvwxyz!@#$%^&*()! "

for char in S:
     if char in alpha:
          count = S.count(char)
     print(char,':',count)

输出

Enter a string: hello
h : 1
e : 1
l : 2
l : 2
o : 1

我希望您能够把它看起来像这样。
Enter a string: hello
    h : 1
    e : 1
    l : 2
    o : 1

我在思考,如果我把字符串和出现字符的数量转换成一个嵌套列表,就像这样:
Enter a string: hello
[['h', 1], ['e', 1], ['l', 2], ['l', 2], ['o', 1]]

我能够删除相同的列表,只留下一个吗?

5个回答

6
>>> s = 'hello'
>>> s = s.lower()
>>> print('\n'.join('{} : {}'.format(c, s.count(c)) for i, c in enumerate(s) if c in "abcdefghijklmnopqrstuvwxyz!@#$%^&*()! " and c not in s[:i]))
h : 1
e : 1
l : 2
o : 1

6
这是使用Python的collections模块中的Counter经典场景:
from collections import Counter

S ='hello'
S = S.lower()
d = Counter(S)
for item, ct in d.items():
    print '%s occured %d times' % (item, ct)

所以计数器就像字典?计数器是一个容器,你可以在其中存储东西。我对它们不太熟悉。 - Mike
是的,Counter 继承自 dict 类。因此,它是一个特殊的字典,用于维护计数。 - Saksham Varma

1
只需迭代一个 set
S = str(input("Enter a string: ")).lower()
alpha = "abcdefghijklmnopqrstuvwxyz!@#$%^&*()! "

for char in set(S):
    if char in alpha:
        print(char,':',S.count(char))

0

你可以做:

S = 'hello'
S = S.lower()
alpha = "abcdefghijklmnopqrstuvwxyz!@#$%^&*()! "

seen=set()

for c in S:
    if c not in seen and c in alpha:
        print '{} : {}'.format(c, S.count(c))
        seen.add(c)

输出:

h : 1
e : 1
l : 2
o : 1

0

所以我想出了一种不使用集合和计数器的方法来完成它。

S = (input("Enter a string: "))
S = S.lower()
alpha = "abcdefghijklmnopqrstuvwxyz!@#$%^&*()! "
L = []
#counts the occurrence of characters in a string.
#then puts them in a list
for char in S:
     if char in alpha:
          count = S.count(char)
     L.append(char)
     L.append(count)
#turns list into a nested list
L2 = []
i = 0
while i <len(L):
        L2.append(L[i:i+2])
        i += 2
#checks that the lists dont appear more than once 
L3 = []
for i in L2:
     if i not in L3:
          L3.append(i)

# print out the letters and count of the letter
for i,k in L3:
     print(i,k)

可能会很长,但它有效。你想对此发表意见吗?


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接