【问题标题】:Need to open text file, print random word with over 5 characters python需要打开文本文件,打印超过5个字符的随机单词python
【发布时间】:2013-08-10 18:27:00
【问题描述】:
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

【问题讨论】:

    标签: python file random


    【解决方案1】:
    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() 的原因。

    【讨论】:

      【解决方案2】:

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

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多