简体   繁体   中英

Need to open text file, print random word with over 5 characters python

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. this code doesnt seem to work for me
  2. here is a link to the file if it helps http://vlm1.uta.edu/~athitsos/courses/cse1310_summer2013/assignments/assignment8/word_list.txt
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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM