2017-06-01 55 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)