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()
答案 0 :(得分: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()
的原因。
答案 1 :(得分: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])