2016-11-24 1 views
0

줄 대신에 'z'를 사용하여 줄 끝을 표시하십시오.파이썬 계산 문자 통계

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]) 
+2

마지막 while 루프에서'print (list [k])'를'print { "} {{}"로 변경하십시오. – inspectorG4dget

답변

0
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]) 

단지 그래서 당신은 대체 할 수 0

의 값 (26 개) 요소를 모두 가진리스트를 생성합니다 thiw와 함께 :이 목록을 구축 할 정말 필요가 없습니다

list = [0] * 26 

그러나 (나중에 볼 수 있듯이). 게다가 변수 이름으로 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: 나는 공간을 계산하고 싶지 않아 믿습니다.

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 

이제이 될 것이다 : 그리고는 Counter

collections에서이 코드를 사용할 수 있습니다 지금이 결과가 정렬되지

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 

,하지만 당신은 아이디어를 얻을. 코드를 추가로 테스트하거나 추가 인쇄 문을 추가 할 수 있습니다.

HTH.