简体   繁体   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. 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 如果文件有帮助,则提供此文件的链接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() . 正如@ ashwini-chaudhary正确指出的那样,迭代的每个步骤上的word最后都有换行符\\n ,这就是为什么需要使用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])

暂无
暂无

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

相关问题 我需要遍历文本文件并从python 3开始并结束满足条件的位置打印特定文本 - I need to iterate over text file and print specific text starting from and end fulfilling condition in python 3 从python中的文本文件中的一行中拉出一个随机单词/字符串 - Pulling a random word/string from a line in a text file in python 如何从 Python 文本文件中的字典中打印随机项目? - How to print a random item from a dictionary that is in a text file on Python? 如何在文本文件中查找一个单词并打印 Python 下一行中的另一个单词 - How to find a word in a text file and print another that is in the next line in Python 如何在文本文件中搜索单词并用 Python 打印整行? - How to search for word in text file and print the entire line with Python? Python:如何在文本文件中打印最短和最长单词? - Python: How to print Shortest and Longest word in a text file? 将下一个单词添加到python中文本文件的列表中,并按列打印 - Append next word into a list from a text file in python and print it columnwise 如何在文本文件中搜索单词并用 Python 打印部分行? - How to search for word in text file and print part of line with Python? (Python)使用for循环在文本文件中打印重复出现的字符 - (Python) Using a for loop to print reoccurring characters in a text file Python搜索文本文件,在字符串后打印字符 - Python search text file, print characters following a string
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM