繁体   English   中英

需要打开文本文件,使用5个以上字符的python打印随机单词

[英]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. 此代码似乎不适合我
  2. 如果文件有帮助,则提供此文件的链接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)

正如@ ashwini-chaudhary正确指出的那样,迭代的每个步骤上的word最后都有换行符\\n ,这就是为什么需要使用rstrip()

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

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])

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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