我想将Python元组转换为.csv
文件。让我们说我有一个retrive()函数,当我用pprint
打印它时,它看起来像这样:
test = tuple(retrive(directory))
pprint(test, width=1)
然后:
("opinion_1.txt, I am an amateur photographer and own three DSLR c.... purchase",
"opinion_2.txt, This my second Sony Digital Came.... good camera for a good price!',
'opinion_3.txt, \'I ordered this camera with high hopes after couldn\\\'t find.\'')
所以,我用csv
模块尝试了这个:
with open('/Users/user/Downloads/output.csv','w') as out:
csv_out=csv.writer(out)
csv_out.writerow(['id','content'])
for row in test:
csv_out.writerow(row)
问题在于我得到一个奇怪的输出,如下所示:
id,content
o,p,i,n,i,o,n,_,1,.,t,x,t,",", ,I, ,a,m, ,a,n, ,a,m,a,t,e,u,r, ,p,h,o,t,o,g,r,a,p,h,e,r, ,a,n,d, ,o,w,n, ,t,h,r,e,e, ,D,S,L,R, ,c,a,m,e,r,a,s, ,w,i,t,h, ,a, ,s,e,l,e,c,t,i,o,n, ,o,f, ,l,e,n,s,e,s,., ,H,o,w,e,v,e,r, ,t,h,a,t, ,c,o,l,l,e,c,t,i,o,n,
我怎样才能得到这样的东西:
opinion_1.txt,I am an amateur photographer and own three DSLR c.... purchase
opinion_2.txt,This my second Sony Digital Came.... good camera for a good price!
opinion_3.txt,I ordered this camera with high hopes after couldn\\\'t find.
答案 0 :(得分:3)
CSV尝试迭代从元组传递的字符串。将您的代码更改为:
for row in test:
csv_out.writerow(row.split(', ', 1))
这意味着您在第一次出现', '
时拆分元组中的每个字符串。
它为每一行产生两个元素,这就是csv writer所需要的。
答案 1 :(得分:1)
如果您需要Pandas
解决方案,请使用DataFrame constructor
和to_csv
:
import pandas as pd
df = pd.DataFrame([ x.split(',') for x in test ])
df.columns = ["id","content"]
print df
# id content
#0 opinion_1.txt I am an amateur photographer and own three DS...
#1 opinion_2.txt This my second Sony Digital Came.... good cam...
#2 opinion_3.txt 'I ordered this camera with high hopes after ...
#for testing
#print df.to_csv(index=False)
df.to_csv("/Users/user/Downloads/output.csv", index=False)
#id,content
#opinion_1.txt, I am an amateur photographer and own three DSLR c.... purchase
#opinion_2.txt, This my second Sony Digital Came.... good camera for a good price!
#opinion_3.txt, 'I ordered this camera with hig
如果有多个,
,您可以在split
首次出现时使用,
:
import pandas as pd
test = ("opinion_1.txt,a","opinion_2.txt,b","opinion_3.txt,c", "opinion_3.txt,b,c,k")
print test
print [ x.split(',', 1) for x in test ]
[['opinion_1.txt', 'a'],
['opinion_2.txt', 'b'],
['opinion_3.txt', 'c'],
['opinion_3.txt', 'b,c,k']]
df = pd.DataFrame([ x.split(',', 1) for x in test ])
df.columns = ["id","content"]
print df
id content
0 opinion_1.txt a
1 opinion_2.txt b
2 opinion_3.txt c
3 opinion_3.txt b,c,k
print df.to_csv(index=False)
id,content
opinion_1.txt,a
opinion_2.txt,b
opinion_3.txt,c
opinion_3.txt,"b,c,k"
答案 2 :(得分:1)
如果你的一个句子有多个这样的逗号,你的解析就会被破坏:
s = "opinion_4.txt, Oh my, what happens with really, really long sentences?"
>>> s.split(", ")
['opinion_4.txt',
'Oh my',
'what happens with really',
'really long sentences?']
更好的方法是找到第一个逗号,然后在此位置使用切片拆分句子:
for line in text:
comma_idx = line.find(', ')
csvout.writerow(line[:comma_idx], line[comma_idx+2:])
对于上面的句子,它会导致:
('opinion_4.txt', 'Oh my, what happens with really, really long sentences?')