1

所以假设我有 5 个文本文件 a.txt、b.txt、c.txt、d.txt、e.txt。我希望能够从每个中读取内容并从每个中调用随机行 a: rand from a.txt b: rand from b.txt 等

到目前为止,这适用于一个文本文件......

import random

contents=[]

with open("a.txt") as a:
    for line in a:
        line=line.strip()
        contents.append(line)

print "Welcome!"
print ""
print "a:", contents[random.randint(0,len(contents)-1)]

为任何帮助欢呼<3

4

2 回答 2

1

使用 foo 循环。

使用randmo.choice而不是random.randint

import os
import random

for filepath in ['a.txt', 'b.txt', 'c.txt', 'd.txt', 'e.txt']:
    with open(filepath) as f:
        lines = [line.strip() for line in f]
    print os.path.splitext(os.path.basename(filepath))[0], ':', random.choice(lines)
于 2013-08-09T07:36:44.807 回答
0

您可以将逻辑放入以文件名作为参数的函数中,同时将随机选择放入该函数中:

import random

def pick_random(filename):
    contents=[]
    with open(filename) as a:
        for line in a:
            line=line.strip()
            contents.append(line)
    return contents[random.randint(0,len(contents)-1)]

print "Welcome!"
print ""
print "a:", pick_random("a.txt")
print "b:", pick_random("b.txt")

您可以为要从中选择一行的每个文件调用该函数,或者像上面那样一个一个地调用它们,或者将所有文件放入一个列表并循环它们。

这是对您的代码的直接扩展,但请考虑 falsetru 的答案以获得更清晰的解决方案。使用random.choice可以更明确地说明您想要完成的任务。

于 2013-08-09T07:36:18.560 回答