2014-02-21 3 views
0

다음은 약 25 행을 포함하는 .csv 파일을 읽는 코드입니다. 출력은 각 행에 대해 동일합니다. 내가 성취 할 수 있기를 원하는 것은 각각의 "행"에 대해 무작위 순서를 갖는 것입니다. 여기에 코드입니다 :파이썬 출력 무작위 순서 ReadLines()

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 만 재정렬해야합니다.

저는 파이썬에서 진보 된 것이 아니며 제 코드가 다르게 수행 될 수 있습니다. 이것은 지금까지이 방법을 알았던 가장 좋은 방법 일뿐입니다. 누군가가 이런 종류의 출력을 얻을 수있는 작동 코드를 얻으려고 노력하면서 제발 나를 도와 줄 수 있습니까? 고맙습니다. CSV 파일에서

SAMPLE 입력 데이터 :

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 BY 원하는 출력 내가 당신을 생각 할

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

죄송합니다. 귀하가하려는 일이 명확하지 않습니다. 원하는 입출력 샘플을 추가 할 수 있습니까? – martineau

+0

몇 가지 샘플 입력 및 출력 데이터를 추가했습니다. 내가 더 잘 설명했으면 좋겠어. – Matt

+0

당신이하려는 일은 아직 명확하지 않습니다. – Nate

답변

1

한 가지 방법 묻고있어. 각 행에 대한 튜플에 도메인/텍스트 쌍을 그룹화 한 다음 해당 목록을 셔플하는 것입니다.

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로 데이터를 사용하여 : 여기

는 셔플 행으로, csv 파일에서 읽어 각 행에 대해 도메인/텍스트 쌍을 셔플, 출력 텍스트 및 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> 

OU tput.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 
+0

정말 고마워요! 이것은 내가해야 할 일이다. 나는 그것을 잘 설명하는 방법을 알지 못했다고 생각하지만, 내가 찾고 있던 것에 대해 잘 생각해 봤다. 이것은 완벽하게 작동합니다. 고맙습니다. – Matt

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