Python计算字符统计

2024-09-27 09:35:57 发布

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

我如何修改附加的程序,以打印信件统计表的形式如下

a=3

b=2个

c=1

并取消使用“z”标记行尾,而不是\r

def getLetIndex(pline, k):
    return pline[k]

print("work with lists or arrays")
list = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26]
k=0
while k < 26:
    list[k]=0
    k +=1
print("list[1]=", list[1])

mline=input("enter a sentence=>")
print("you have entered=", mline)
k=0
while k < 26:
    k+= 1
    oneChar = getLetIndex(mline, k)
    if oneChar == 'z':
        break
    num1 = ord(oneChar)
    print("char=", oneChar, "char-num=", num1)
    if num1 != 32:                  # not space
        list[num1-97+1] += 1
print("letter statistics are below")
k=0
while k < 26:
    print(list[k])
    k +=1
print("list[1]=", list[1])

Tags: 标记程序if形式listprint信件char
1条回答
网友
1楼 · 发布于 2024-09-27 09:35:57

这个:

list = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26]
k=0
while k < 26:
    list[k]=0
    k +=1
print("list[1]=", list[1])

只生成一个包含26个元素的列表,所有元素的值都是0

所以你可以用以下内容代替这个:

^{pr2}$

但是,实际上并不需要构建这个列表(您将在后面看到)。此外,您不应该使用单词list作为变量名。在

您还可以执行以下操作:

while k < 26:
    k+= 1
    oneChar = getLetIndex(mline, k)
    if oneChar == 'z':
        break
    num1 = ord(oneChar)
    print("char=", oneChar, "char-num=", num1)
    if num1 != 32:                  # not space
        list[num1-97+1] += 1

很明显,您希望循环26次,并在遇到行尾字符时停止,该字符由代码设置为z。你也不必那么做。另一个限制是,如果输入的句子超过26个字符,会发生什么?在

如果num1 != 32:我相信你不想计算空格。 让我们使用来自collectionsCounter

此代码:

mline=input("enter a sentence=>")
print("you have entered=", mline)
k=0
while k < 26:
    k+= 1
    oneChar = getLetIndex(mline, k)
    if oneChar == 'z':
        break
    num1 = ord(oneChar)
    print("char=", oneChar, "char-num=", num1)
    if num1 != 32:                  # not space
        list[num1-97+1] += 1

现在将变成:

from collections import Counter

mline=input("enter a sentence=>")  
mline = mline.replace(" ","")             # this will get rid of spaces
c = Counter(mline)                        # create a counter object
for char, count in c.items():             # enumerate through the items
    print("{} = {}".format(char, count))  # print the result

现在这个结果没有排序,但是你知道了。 现在,您可以进一步试验代码,添加额外的print语句,或者其他任何您想做的事情。在

好吧。在

相关问题 更多 >

    热门问题