gpt4 book ai didi

python - 从多个文本文件中调用随机行

转载 作者:太空宇宙 更新时间:2023-11-03 18:51:56 28 4
gpt4 key购买 nike

假设我有 5 个文本文件 a.txt、b.txt、c.txt、d.txt、e.txt。我希望能够读取每个内容并从每个内容中调用随机行a:a.txt 中的兰特b: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

最佳答案

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

关于python - 从多个文本文件中调用随机行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18142024/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com