Python从ReadLines()输出随机顺序

Python从ReadLines()输出随机顺序,python,random,Python,Random,下面是我用来读取包含大约25行的.csv文件的代码。每行的输出相同。我希望能够做到的是对每一行有一个随机顺序。代码如下: f_in = open("input.csv",'r') f_out = open('output.txt', 'w') for line in f_in.readlines(): f_out.write('<p>' + random.choice(list(open('content.txt'))).replace("\n", "").replace(

下面是我用来读取包含大约25行的.csv文件的代码。每行的输出相同。我希望能够做到的是对每一行有一个随机顺序。代码如下:

f_in = open("input.csv",'r')

f_out = open('output.txt', 'w')
for line in f_in.readlines():
    f_out.write('<p>' + random.choice(list(open('content.txt'))).replace("\n", "").replace(".", "").replace("?", "").strip().capitalize() + ' <a href="' +
                line.replace("\n", "").split(",")[0]+"" + '">' + line.replace("\n", "").split(",")[1]+"" + '</a> ' + random.choice(list(open('content.txt'))).replace("\n", "").strip().lower() + '</p>' + 
                #
                '<p>' + random.choice(list(open('content.txt'))).replace("\n", "").replace(".", "").replace("?", "").strip().capitalize() + ' <a href="' +
                line.replace("\n", "").split(",")[2]+"" + '">' + line.replace("\n", "").split(",")[3]+"" + '</a> ' + random.choice(list(open('content.txt'))).replace("\n", "").strip().lower() + '</p>' + 
                #
                '<p>' + random.choice(list(open('content.txt'))).replace("\n", "").replace(".", "").replace("?", "").strip().capitalize() + ' <a href="' +
                line.replace("\n", "").split(",")[4]+"" + '">' + line.replace("\n", "").split(",")[5]+"" + '</a> ' + random.choice(list(open('content.txt'))).replace("\n", "").strip().lower() + '</p>' +
                #
                '\n')    
f_in.close()
f_out.close()
CSV数据

http://domain.com,anchor text 1,http://domain2.com,anchor text 2,http://domain3.com,anchor text 3
http://domain.com,anchor text 1,http://domain2.com,anchor text 2,http://domain3.com,anchor text 3
http://domain.com,anchor text 1,http://domain2.com,anchor text 2,http://domain3.com,anchor text 3
所需的行输出

Line 1 --> Column A and B Column E and F Column C and D
Line 2 --> Column E and F Column A and B Column C and D
Line 3 --> Column C and D column E and F Column A and B

一种方法是将域/文本对分组为每行的元组,然后洗牌该列表

下面是一些代码,这些代码将从csv文件中读取,对每行的域/文本对进行无序排列,并使用无序排列的行输出文本和csv文件:

import random
import csv

with open("input.csv") as infile:
    csvreader = csv.reader(infile)
    with open("output.csv", 'w') as outcsv:
        csvwriter = csv.writer(outcsv)
        with open("output.txt", 'w') as outtxt:
            for row in csvreader:
                random_pairs = [(row[2*i], row[2*i + 1]) for i in range(int(len(row)/2))]
                random.shuffle(random_pairs)
                outline = []
                for pair in random_pairs:
                    outtxt.write('<a href="' + pair[0] + '">' + pair[1] + '</a>')
                    outline.append(pair[0])
                    outline.append(pair[1])
                outtxt.write('\n')
                csvwriter.writerow(outline)

我试图将代码分解成函数;它应该更容易理解和维护

import csv
from itertools import izip
import random

LOREM_IPSUM = "content.txt"
LINK_TEXT   = "input.csv"
OUTPUT      = "output.phtml"

def csv_rows(fname, **kwargs):
    with open(fname, "rb") as inf:
        incsv = csv.reader(inf, **kwargs)
        for row in incsv:
            yield row

def by_twos(iterable):
    # given (a, b, c, d, ...) returns ((a,b), (c,d), ...)
    return izip(*([iter(iterable)]*2))

def a(href, *content):
    return "<a href=\"{0}\">{1}</a>".format(href, " ".join(content))

def p(*content):
    return "<p>{0}</p>".format(" ".join(content))

def br():
    return "<br/>"

def main():
    with open(LOREM_IPSUM) as inf:
        lines = (line.strip() for line in inf)
        content = [line.capitalize() for line in lines if line]
    randtxt = lambda: random.choice(content)

    with open(OUTPUT, "w") as outf:
        for row in csv_rows(LINK_TEXT):
            links = [a(href, text) for href,text in by_twos(row)]
            random.shuffle(links)    # randomize order
            paras = (p(randtxt(), link, randtxt()) for link in links)
            outf.write("".join(paras))
            outf.write(br())

if __name__=="__main__":
    main()
导入csv
从itertools导入izip
随机输入
LOREM_IPSUM=“content.txt”
LINK_TEXT=“input.csv”
OUTPUT=“OUTPUT.phtml”
def csv_行(fname,**kwargs):
以open(fname,“rb”)作为inf:
incsv=csv.reader(inf,**kwargs)
对于incsv中的行:
产量行
def由两个(可编辑):
#给定(a,b,c,d,…)返回((a,b),(c,d),…)
返回izip(*[iter(iterable)]*2))
def a(href,*内容):
返回“.格式(href)”.join(内容))
def p(*内容):
返回“{0}

”.format(“.join(content)) def br(): 返回“
” def main(): 以open(LOREM_IPSUM)作为inf: lines=(inf中的行的line.strip()) content=[line.capitalize()表示行中的行,如果是行] randtxt=lambda:random.choice(内容) 以开放式(输出,“w”)作为出口: 对于csv_行中的行(链接_文本): links=[a(href,text)for href,text in by_twos(row)] 随机。随机排列(链接)#随机排列顺序 段落=(p(randtxt(),link,randtxt())表示链接中的链接) 写出(“.”连接(第段)) outp.write(br()) 如果名称=“\uuuuu main\uuuuuuuu”: main()
对不起,不清楚您想做什么。您能添加所需输入和输出的示例吗?我添加了一些示例输入和输出数据。我希望我能解释得更好。你想做什么还不是很清楚。输入文件在我看来不像CSV格式。如果可能,请显示文件中的实际行。我在.CSV文件的CSV数据下更新了它。非常感谢!这正是我需要做的。我想我不知道该怎么解释,但你在了解我所寻找的方面做得很好。这很好用。非常感谢。
<a href="http://domain3.com">anchor text 3</a><a href="http://domain2.com">anchor text 2</a><a href="http://domain.com">anchor text 1</a>
<a href="http://domain3.com">anchor text 3</a><a href="http://domain.com">anchor text 1</a><a href="http://domain2.com">anchor text 2</a>
<a href="http://domain2.com">anchor text 2</a><a href="http://domain3.com">anchor text 3</a><a href="http://domain.com">anchor text 1</a>
http://domain3.com,anchor text 3,http://domain2.com,anchor text 2,http://domain.com,anchor text 1
http://domain3.com,anchor text 3,http://domain.com,anchor text 1,http://domain2.com,anchor text 2
http://domain2.com,anchor text 2,http://domain3.com,anchor text 3,http://domain.com,anchor text 1
import csv
from itertools import izip
import random

LOREM_IPSUM = "content.txt"
LINK_TEXT   = "input.csv"
OUTPUT      = "output.phtml"

def csv_rows(fname, **kwargs):
    with open(fname, "rb") as inf:
        incsv = csv.reader(inf, **kwargs)
        for row in incsv:
            yield row

def by_twos(iterable):
    # given (a, b, c, d, ...) returns ((a,b), (c,d), ...)
    return izip(*([iter(iterable)]*2))

def a(href, *content):
    return "<a href=\"{0}\">{1}</a>".format(href, " ".join(content))

def p(*content):
    return "<p>{0}</p>".format(" ".join(content))

def br():
    return "<br/>"

def main():
    with open(LOREM_IPSUM) as inf:
        lines = (line.strip() for line in inf)
        content = [line.capitalize() for line in lines if line]
    randtxt = lambda: random.choice(content)

    with open(OUTPUT, "w") as outf:
        for row in csv_rows(LINK_TEXT):
            links = [a(href, text) for href,text in by_twos(row)]
            random.shuffle(links)    # randomize order
            paras = (p(randtxt(), link, randtxt()) for link in links)
            outf.write("".join(paras))
            outf.write(br())

if __name__=="__main__":
    main()