【问题标题】:Converting texts in to csv file under separate columns在单独的列下将文本转换为 csv 文件
【发布时间】:2020-08-21 07:50:11
【问题描述】:

我在 .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

【问题讨论】:

  • 你的错误是什么?
  • 没有错误。只是没有得到正确的格式。请查看上面的当前输出和所需的理想输出。
  • SO 不是:写代码服务。如果您需要针对特定​​错误的帮助,那么寻求帮助是合适的。

标签: python-3.x csv text export-to-csv


【解决方案1】:

使用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, 'w', 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

【讨论】:

  • 解析第一行数据后。我也收到错误ValueError: malformed node or string: ["['LG','Samsung','Asus','HP','Apple','HTC']"]
猜你喜欢
  • 1970-01-01
  • 2021-11-26
  • 2020-03-08
  • 1970-01-01
  • 2021-03-11
  • 1970-01-01
  • 2018-01-31
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多