'Python 2.7字符串索引E'

2024-05-16 10:47:35 发布

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

我正在编写一个程序,从文本文件中选择一个随机行,使用while循环作为计数器,然后使用另一个变量来选择随机行:

import random 


fortunes_file = open("fortunes.txt", "r")


fortunes = fortunes_file.readline()

count = 0


while fortunes != "":
    count += 1
    fortunes = fortunes_file.readline()

rand_line = random.randint(1, count)

print fortunes[rand_line]

fortunes_file.close()

但是,在尝试运行程序时出现以下错误:

IndexError: string index out of range

Tags: import程序txtreadlinecountline计数器random
3条回答

问题在于:

fortunes = fortunes_file.readline()

...

    fortunes = fortunes_file.readline()

您刚刚重新定义了变量,因此在while循环结束之后,fortunes实际上是文件中的最后一行。你知道吗


只需使用^{}逐行将文件读入列表,然后使用^{}随机选择列表中的元素。你不需要一个计数器,也不需要自己来切分列表。你知道吗

例如:

import random   

# use `with` is recommended here since you don't need close the file manually
with open("fortunes.txt", "r") as f:
    fortunes = fortunes_file.readlinse()

print random.choice(fortunes)

但是,如果您还想知道如何修复代码,只需将^{}的输出放入如下列表中:

import random 


fortunes_file = open("fortunes.txt", "r")    

fortunes = []
fortunes.append(fortunes_file.readline())   
count = 0


while fortunes != "":
    count += 1
    fortunes.append(fortunes_file.readline())

rand_line = random.randint(1, count)

print fortunes[rand_line]   
fortunes_file.close()

请注意,如果您不想使用.readlines()random.choice(),您仍然不需要该计数器,您也可以使用^{}来获取列表的长度,而不是自己编写一个无用的计数器。你知道吗

您需要readlines()而不是readline();但实际上,您可以高度简化代码:

import random

with open('fortunes.txt') as f:
   fortunes = list(f)

print(random.choice(fortunes))

或者,如果您更喜欢readlines()版本:

import random

f = open('fortunes.txt')
fortunes = f.readlines()
f.close()

print(random.choice(fortunes))

while循环的每次迭代中,您都要覆盖fortunes。 在EOF处^{}返回一个空字符串,因此fortunes[rand_line]引发IndexError。您可以改用^{}(或者将file对象用作迭代器):

with open("fortunes.txt", "r") as fortunes_file:
    fortunes = fortunes_file.readlines()  # alternatively, use list(fortunes_file)
print(random.choice(fortunes))

相关问题 更多 >