如何在 python 中逐行读取文本文件

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(), then readlines(), then random.choice():

    import random
    line = random.choice(open("file").readlines())
    
  • 如果您尝试从三个列表中的每一个中选择一个随机元素,您可以使用 random.choice():

    import random
    choices=[random.choice(i) for i in lists]
    

    lists 是可供选择的列表列表。

这些答案帮助我从文本文件的列表中抓取内容。正如您在下面的代码中看到的那样。但是我有三个列表作为文本文件,我试图随机生成一个 4 字的消息,从 'prefix' 和 'suprafix' 列表中选择前 3 个单词,从 'suffix' 文件中选择第四个word 但我想防止它在打印它们时选择 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 个词