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()
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)
As @ashwini-chaudhary correctly pointed out, word
on each step of iteration has newline \\n
at the end - that's why you need to use rstrip()
.
Assuming each word is on it's own line such as:
word
word2
word3
...
then you can do this:
from random import choice
with open("word_list.txt") as file:
print choice([line.rstrip() for line in file if len(line) > 5])
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.