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

时间:2015-03-24 05:34:23

标签: python string

我被要求从用户输入中计算字符串中字母和空格以及标点符号的出现次数,并且在打印输出中字母应按照它们出现在文本中的顺序出现,但不应出现两次字母小写和大写应该算作一个。到目前为止我的代码看起来像这样。

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 个答案:

答案 0 :(得分: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

答案 1 :(得分:6)

这是使用Counter模块的collections的典型情况:

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)

答案 2 :(得分: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))

答案 3 :(得分: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

答案 4 :(得分: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)

可能很长但是有效。想要你的意见吗?