簡體   English   中英

Python輸出隨機順序來自ReadLines()

[英]Python Output Random Order From ReadLines()

下面是我讀取包含大約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()

這輸出的是<p>text a link text</p><p>text a link text</p><p>text a link text</p>這很好,這就是我想要的但我需要排2以不同的順序以及第3行等等。

例如,它從第1行讀取的第一個輸出將是列AB CD EF,我想要的是第2行輸出為EF AB CD列。 因此,對於.csv文件中的每一行,輸出需要重新排序,而不僅僅是針對.csv文件中每25行的AB CD EF。

我在Python中並不是真正先進的,我的代碼可以用不同的方式完成,這只是我知道如何實現這一目標的最佳方式。 有人可以通過嘗試獲得能夠實現此類輸出的工作代碼來幫助我嗎? 謝謝。

從CSV文件中輸入數據樣本:

Line 1 --> Column A http://domain.com Column B my anchor text 1 Column C http://domain.com Column D my anchor text 2 Column E http://domain.com Column F my anchor text 3
Line 2 --> Column A http://domain.com Column B my anchor text 1 Column C http://domain.com Column D my anchor text 2 Column E http://domain.com Column F my anchor text 3
Line 3 --> Column A http://domain.com Column B my anchor text 1 Column C http://domain.com Column D my anchor text 2 Column E http://domain.com Column F my anchor text 3

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文件中讀取,為每行的域/文本對進行洗牌,並輸出帶有混洗行的text和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)

使用您提供的csv數據會產生以下輸出:

output.txt的:

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

output.csv:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM