Email,Division,Department
预期产出:
Email,Division,Department
答案 0 :(得分:0)
我认为您的文件不是真正的csv文件。 但你可以尝试这些代码,我认为它有效。
def convert(strs):
array=[]
if len(strs)==4:
array.append({
'left':strs[0],
'right':strs[2]
})
array.append({
'left':strs[1],
'right':strs[3]
})
else:
array.append({
'left':strs[0],
'right':strs[1]
})
return array
file='/Users/lidl/example.csv'
sumarray=[]
for line in open(file):
line=",".join(line.split())# rebuild a str line with comma segmentation
strs=line.split(",")
sumarray=sumarray+convert(strs)
for item in sumarray:
print(item['left']+" "+item['right'])
抱歉代码格式不好。
答案 1 :(得分:0)
这是一个快速的Ruby版本:
#!/usr/bin/ruby
# header
puts STDIN.gets
while line = STDIN.gets
left, right = line.split
left = left.split(',')
right = right.split(',')
left.each_with_index{ |item, i|
break unless right[i]
puts item + "\t" + right[i]
}
end
测试:
$ cat /tmp/test | /tmp/test.rb
Division Department
tech qa
ux ui
tech server
prod prod
sales sales
答案 2 :(得分:0)
Python Power Unleased:
import csv,sys
filename = 'a.csv'
with open(filename,'rb') as csvfile:
reader = csv.reader(csvfile,delimiter=',')
try:
for row in reader:
if row[1].find(',') == -1:
line = ','.join(row)
print line
else:
for i in range(0,row[1].count(',')+1):
line = row[0]+','+row[1].split(',')[i]+','+row[2].split(',')[i]
print line
except csv.Error as e:
sys.exit('file %s, line %d: %s' % (filename, reader.line_num, e))