2014-02-27 199 views
1

我目前在我的Python腳本中調用了一個python腳本,並試圖將我的調用輸出保存在一個CSV文件中。但是,現在它可以工作,但每個字符之間都會有逗號,所以輸出不正確。CSV.writerow在每個字符之間都有逗號?

這是什麼造成的?

import csv 
import GetAlexRanking #External Method exposed here 
import subprocess 
import pandas as p 
import tai 
import numpy as np 

loadData = lambda f: np.genfromtxt(open(f,'r'), delimiter=' ') 
with open('train.tsv','rb') as tsvin, open('PageRanks.csv', 'wb') as csvout: 
    tsvin = list(np.array(p.read_table('train.tsv'))[:,0]) 
    csvout = csv.writer(csvout) 

    for row in tsvin: 
     count = 0 
     cmd = subprocess.Popen("python GetAlexRanking.py " + row , 
          stdout=subprocess.PIPE, 
          stderr=subprocess.PIPE, 
          shell=True) 
     (output, err) = cmd.communicate() 
     exit_code = cmd.wait() 
     print exit_code #testing 
     print output 
     print err 
     csvout.writerow(row + "\t" + output) #writing,error here 
     count+=1 

編輯:

在cmd中稱爲像這樣"python GetAlexRanking.py www.google.com"當從函數返回的樣本行:

www.google.com 
AlexaTrafficRank:1 
GooglePageRank:9 

我想這是保存在TSV爲使(空格添加以使格式更清晰,所有列僅由製表符分隔:))

URL \t AlexaRank \t GoogleRank 
www.google.com \t 1 \t 9 
+0

請展示了一個排,看起來輸出什麼樣,什麼它應該看起來像。請注意,第一個輸出到csv文件應該是標題行。你考慮過csv.DictWriter()嗎? – sabbahillel

+0

請給出'tsvin'的示例元素。我只能假設'tsvin = list(np.array(p.read_table('train.tsv'))[:, 0])'實際上是返回一個單一的字符串,然後調用list()將它分成小塊。例如。; >>> list(「helloworld」) ['h','e','l','l','o','w','o','r','l',' d'] – sleepycal

+0

@sabbahillel問題更新(我相信)所有信息。非常感謝你! –

回答

3

您將一個字符串傳遞給csv.write,然後它將其解釋爲一個列表,然後將其分割爲每個列表元素(即字符)。我犯了這個錯誤太多次......

試試這個:

# add coustom code to split the row up into the values, hint user row.split() 
csvout.writerow([row, output]) 
1

看起來,如果你希望你的輸入是一個清單,以及您的輸出。因此,讓您的輸入保留一組字符串並將其分割成每行的列表。

您返回的樣品行顯示在三行中。這是否意味着它是一個具有列分隔符的長字符串?如果是這種情況,請分割輸出並插入選項卡。

outrow = row # row is already a list 
    outrow.append(output.split('\t')) 
    csvout.writerow(outrow) 

再次看看您的示例,看起來您要輸出兩個tsv行,一個帶有「標題」,另一個帶有「等級」。因此(與多餘的線條爲了便於閱讀)

outlist = output.split('\t') 
outname1 = outlist[1][0:outlist[1].index(':')-1] 
outname2 = outlist[2][0:outlist[2].index(':')-1] 
outrank1 = outlist[1][outlist[1].index(':')+1:] 
outrank2 = outlist[2][outlist[2].index(':')+1:] 
outrow1 = ['URL', outname1, outname2] 
outrow2 = [outlist[0], outrank1, outrank2] 

你可以這樣寫兩個輸出行,你好像把已經於您的樣本輸出

+0

@sabbaillel謝謝你的迴應,但我很努力地理解這一點。我想保存我的輸出製表符分隔,在輸出的第一行中有一組列標題。你能告訴我如何使用你的代碼來完成這個任務嗎?不便之處敬請原諒。 –

+0

只是爲了補充一點;此代碼不會運行錯誤:文件「GeneratePageRanks.py」,第23行,在 outrow.append(output.split('\ t')) AttributeError:'str'object has no attribute'append' –

相關問題