2017-06-01 77 views
-2

我不知道爲什麼,我不斷收到錯誤「字符串索引超出範圍」和其他錯誤在線47個print_data(數據。可有人請解釋爲什麼?謝謝錯誤與我的代碼?字符串索引超出範圍?

def open_file(): 
    user_input = input('Enter a file name: ') 
    try: 
    file = open(user_input, 'r') 
    return file 
    except FileNotFoundError: 
    return open_file() 


def read_data(file): 
    counter = [0 for _ in range(9)] 
    for line in file.readlines(): 
    num = line.strip() 
    if num.isdigit(): 
     i = 0 
     digit = int(num[i]) 
     while digit == 0 and i < len(num): 
     i += 1 
     digit = int(num[i]) 
     if digit != 0: 
     counter[digit - 1] += 1 
    return counter 


def print_data(data): 
    benford = [30.1, 17.6, 12.5, 9.7, 7.9, 6.7, 5.8, 4.1, 4.6] 
    header_str = "{:5s} {:7s}{:8s}" 
    data_str = "{:d}:{:6.1f}% ({:4.1f}%)" 
    total_count = sum(data) 
    print(header_str.format("Digit", "Percent", "Benford")) 
    for index, count in enumerate(data): 
    digit = index + 1 
    percent = 100 * count/total_count 
    print(data_str.format(digit, percent, benford[index])) 


def main(): 
    file = open_file() 
    data = read_data(file) 
    print_data(data) 
    file.close() 

if __name__ == "__main__": 
    main() 

這是確切的錯誤我給

Traceback (most recent call last): 
    File "./lab08.py", line 52, in <module> 
    main() 
    File "./lab08.py", line 47, in main 
    data = read_data(file) 
    File "./lab08.py", line 26, in read_data 
    digit = int(num[i]) 
+1

你切斷錯誤消息的一部分。 – user2357112

+0

你可以在文件中給出一個示例行嗎? – Rosh

+0

無法重現錯誤:我們需要足夠的輸入文件來引發問題。 – Prune

回答

2

我相信,錯誤源於此:

while digit == 0 and i < len(num): i += 1 digit = int(num[i])

如果英語新WAP第二兩行,則能正確指數,即:

while digit == 0 and i < len(num): digit = int(num[i]) i += 1

如果,例如,你的字符串num是長度爲10的,那麼最終元件是在索引9(從0索引)。對於該循環的第一次迭代,您將有數字爲num[1],對於第十次迭代,您應該是num[10]

的另一種方法是使用列表理解是這樣的: for n in num: if digit != 0: break digit = int(n)