1

我想从文本文件中随机检索并打印一整行。

文本文件基本上是一个列表,因此需要搜索该列表中的每个项目。

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

这是我的代码,如果我只是手动将其输入到列表中,但我似乎无法找到如何使用数组或索引逐行捕获文本并使用它

4

3 回答 3

0

使用 Python 的file.readLines()方法:

with open("file_name.txt") as f:
    prefix = f.readlines()

现在您应该能够遍历列表prefix

于 2015-03-18T21:39:03.393 回答
0

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

于 2015-03-18T23:02:55.540 回答
0

我不确定我是否完全理解您的要求,但我会尽力提供帮助。

  • 如果您尝试从文件中选择随机行,则可以使用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是可供选择的列表列表。

于 2015-03-18T21:44:54.580 回答