Separate a row of strings into separate rows [clos

2019-03-07 17:36发布

Email,Division,Department

Expected output:

Email,Division,Department

3条回答
放我归山
2楼-- · 2019-03-07 18:14

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))
查看更多
来,给爷笑一个
3楼-- · 2019-03-07 18:22

Here is a quick Ruby version:

#!/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

Test:

$ cat /tmp/test | /tmp/test.rb
Division    Department
tech    qa
ux      ui
tech    server
prod    prod
sales   sales
查看更多
\"骚年 ilove
4楼-- · 2019-03-07 18:35

I don't think your file is a real csv file. But you can try this codes ,I think it works.

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'])

sorry for the codes bad format.

查看更多
登录 后发表回答