如何在csv文件中连接行

时间:2017-11-01 03:26:27

标签: python

我有一个这种格式的csv文件(1000行):

What, WP
makes, VBZ
them, PRP
do, VB

它的单词和TAG,我想加入标签以使图形的边缘为例如边缘应该是..

WP,VBZ
VBZ,PRP
PRP,VB
VB,PRP

依此类推..到目前为止,我设法只拆分列表中的标签

files = glob.glob('C:/Users/Sebastian/Desktop/nodos/*.csv')

  for path in files:
     dirname, filename = os.path.split(path)
     with open('C:/Users/Sebastian/Desktop/nodos/%s' %filename) as 
     csvfile,open('C:/Users/Sebastian/Desktop/aristas/%s' %filename,'w') as 
     output:   
    csv_reader = csv.reader(csvfile, delimiter=',')
    for row in csv_reader:          
         output.write(row[1])                   
         output.write('\n')

我得到了

WP
VBZ
PRP
VB
...

2 个答案:

答案 0 :(得分:0)

files = glob.glob('C:/Users/Sebastian/Desktop/nodos/*.csv')

  for path in files:
     dirname, filename = os.path.split(path)
     with open('C:/Users/Sebastian/Desktop/nodos/%s' %filename) as 
     csvfile,open('C:/Users/Sebastian/Desktop/aristas/%s' %filename,'w') as 
     output:   
    csv_reader = csv.reader(csvfile, delimiter=',')

    isFirstRow = True;
    for row in csv_reader:  
         if isFirstRow:
           prevRow1 = row[1]
           isFirstRow = False
         else:        
           output.write(prevRow1 + ',' + row[1])                   
           output.write('\n')
           prevRow1 = row[1]

答案 1 :(得分:0)

你可以这样做:

out = []
prev = None
for row in list(csv_reader):
    if prev is not None: out.append(prev + "," + row[1])
    prev = row[1]

对于包含以下内容的csv文件:

What, WP
makes, VBZ
them, PRP
do, VB

<强>输出

>>> out
['WP,VBZ', 'VBZ,PRP', 'PRP,VB']

然后您可以执行,output.writelines(out)将此内容写入文件(在上面的for循环之后)。