Python从文件中获取多个随机行

时间:2015-04-24 21:10:36

标签: python random

有人可以帮助我这么快吗?这是我正在使用的代码:

# Lists:
anchorslist = []

#Files:
anchors = open(basepath + "anchors.txt", "r")

#Placed In List:
for line in anchors:
        anchorslist.append(line.replace("\n", "|"))

#Used:
type(anchorslist)

它将从我的文本文件中返回一个随机行。我想要实现的是让我们说10个随机返回的行如下:

random_anchor1|random_anchor2|random_anchor3|random_anchor4

我随机使用它。

def type(name):
    value = name[random.randint(0,len(name)-1)]
    return value

我如何修改代码以返回?感谢。

2 个答案:

答案 0 :(得分:3)

 '|'.join(random.sample(anchorlist,10))

random.sample(anchorlist,10)从anchorlist

返回10个随机元素

'|'.join(...)使用|作为分隔符

连接列表

答案 1 :(得分:2)

你想要使用的是random python模块。有了它,您可以使用random.choice(anchorlist)从列表中选择一个随机行。以下是一些可以实现此目的的代码:

import random
# Lists:
anchorslist = []

#Files:
anchors = open("anchors.txt", "r")

#Placed In List:
for line in anchors:
        anchorslist.append(line.replace("\n", "|"))

anchors.close()

rand_options = anchorslist  # duplicate list, better than editting the input list
rand_vals = []
length = 3  # configure to 10, or how ever many random lines you want

for _ in range(length):
    rand_val = random.choice(rand_options)
    rand_vals.append(rand_val)    
    rand_options.remove(rand_val)  # remove from list so you don't get duplicates (unless you don't mind those)

what_you_want = "".join(rand_vals).rstrip("|")

说anchors.txt ="你好\ n我是\ n \ n \ n \ n \ n \ n \ n随机\ n的东西",     what_you_want ="我|东西|你好"