[英]I need to iterate over text file and print specific text starting from and end fulfilling condition in python 3
[英]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()
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.