1
import random
dictionary = open('word_list.txt', 'r')
for line in dictionary:

    for i in range(0, len(line)):
        if i >= 5:    
            word = random.choice(line)
dictionary.close()
  1. 这段代码似乎对我不起作用
  2. 如果有帮助,这里是文件的链接 http://vlm1.uta.edu/~athitsos/courses/cse1310_summer2013/assignments/assignment8/word_list.txt
4

2 回答 2

0
import random

with open('word_list.txt', 'r') as f:
    words = [word.rstrip() for word in f if len(word) > 5]

print random.choice(words)

正如@ashwini-chaudhary 正确指出的那样,word在迭代的每一步\n最后都有换行符 - 这就是你需要使用rstrip().

于 2013-08-10T18:28:54.140 回答
0

假设每个单词都在它自己的行上,例如:

word
word2
word3
...

那么你可以这样做:

from random import choice
with open("word_list.txt") as file:
    print choice([line.rstrip() for line in file if len(line) > 5])
于 2013-08-10T18:31:19.280 回答