将文本转换为单独列下的csv文件

问题描述

.txt文件中包含以下内容

1.['LG','Samsung','Asus','HP','Apple','HTC']
2.['covid','vaccine','infection','cure','chloroquine']
3.['p2p','crypto','bitcoin','litecoin','blockchain']

如何将以上内容转换为不同列下的csv文件

我当前的代码是这个

import csv

with open('Full_txt_results.txt','r') as in_file:
    stripped = (line.strip() for line in in_file)
    lines = (line.split(",") for line in stripped if line)
    with open('textlabels.csv','w') as out_file:
        writer = csv.writer(out_file)
        writer.writerows(lines)

代码当前在csv中以以下格式给出结果

Column 1  Column2   column 3   column 4     Column 5        column 6
['LG'    'Samsung'  'Asus'       'HP'       'Apple'        'HTC']
['covid' 'vaccine' 'infection'  'cure'    'chloroquine']
['p2p'   'crypto'  'bitcoin'   'litecoin'  'blockchain']

这些文本会溅到不同的列中。

所需的理想输出格式如下

Column 1  Column2     column 3   
LG        Covid         p2p
Samsung   Vaccine      crypto
Asus      Infection    bitcoin
HP        cure         litecoin
Apple     chloroquine  blockchain  
HTC

解决方法

使用ast模块将字符串转换为列表对象,然后使用writerow方法写入csv

例如:

import csv
import ast

with open('Full_txt_results.txt') as in_file,open('textlabels.csv','w',newline="") as out_file:
    writer = csv.writer(out_file)
    data = [ast.literal_eval(line.strip().split(".")[1]) for line in in_file]      #If you do not have column number(1.,2.,...) Use [ast.literal_eval(line.strip()) for line in in_file]
    for row in zip(*data):
        writer.writerow(row)

演示

import csv
import ast

with open(filename) as in_file,open(outfile,newline="") as out_file:
    writer = csv.writer(out_file)
    data = [ast.literal_eval(line.strip()) for line in in_file]
    for row in zip(*data):
        writer.writerow(row)

SRC txt文件

['LG','Samsung','Asus','HP','Apple','HTC']
['covid','vaccine','infection','cure','chloroquine']
['p2p','crypto','bitcoin','litecoin','blockchain']

输出:

LG,covid,p2p
Samsung,vaccine,crypto
Asus,infection,bitcoin
HP,cure,litecoin
Apple,chloroquine,blockchain