[英]How to read a text file by line in python
我想从文本文件中随机检索并打印整行。
文本文件基本上是一个列表,因此该列表中的每个项目都需要搜索。
import random
a= random.random
prefix = ["CYBER-", "up-", "down-", "joy-"]
suprafix = ["with", "in", "by", "who", "thus", "what"]
suffix = ["boy", "girl", "bread", "hippy", "box", "christ"]
print (random.choice(prefix), random.choice(suprafix), random.choice(prefix), random.choice(suffix))
这是我的代码,如果我只是手动将其输入到列表中,但是我似乎找不到如何使用数组或索引来逐行捕获文本并使用该代码的代码
使用Python的file.readLines()方法:
with open("file_name.txt") as f:
prefix = f.readlines()
现在您应该可以遍历列表prefix
。
我不确定我是否完全理解您的要求,但我会尽力提供帮助。
如果您尝试从文件中选择随机行,则可以使用open()
,然后使用readlines()
,然后使用random.choice()
:
import random line = random.choice(open("file").readlines())
如果您试图从三个列表中的每个列表中选择一个随机元素,则可以使用random.choice()
:
import random choices=[random.choice(i) for i in lists]
lists
是从此处选择的列表列表。
这些答案帮助我从文本文件列表中获取内容。 如下面的代码所示。 但是我有三个列表作为文本文件,我试图随机生成一个4字的消息,对于前3个字,从'prefix'和'suprafix'列表中选择,对于第四个字,则选择'suffix'文件,但是我想防止在打印它们时,从选择random.choice函数已经选择的单词开始
import random a= random.random prefix = open('prefix.txt','r').readlines() suprafix = open('suprafix.txt','r').readlines() suffix = open('suffix.txt','r').readlines() print (random.choice(prefix + suprafix), random.choice(prefix + suprafix), random.choice(prefix + suprafix), random.choice(suffix))
如您所见,它从这2个列表中随机选择3个词
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.