簡體   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