分为两列,然后将txt文本转换为csv文件

时间:2018-12-12 18:26:47

标签: python python-3.x

我有以下数据:

Graudo. A selection of Pouteria caimito, a minor member...

TtuNextrecod. A selection of Pouteria caimito, a minor member of the Sapotaceae...

我想将其分为两列

Column1       Column2
------------------------------------------------------------------------------
Graudo        A selection of Pouteria caimito, a minor member...
TtuNextrecod  A selection of Pouteria caimito, a minor member of the Sapotaceae...

需要帮助的代码。谢谢,

import csv # convert
import itertools #function for a efficient looping

with open('Abiutxt.txt', 'r') as in_file:
    lines = in_file.read().splitlines() #returns a list with all the lines in string, including the line breaks

    test = [line.split('. ')for line in lines ] #split period....but...need work

    print(test)


    stripped = [line.replace('', '').split('. ')for line in lines ]

    grouped = itertools.izip(*[stripped]*1)
    with open('logtestAbiutxt.csv', 'w') as out_file:
        writer = csv.writer(out_file)
        writer.writerow(('Column1', 'Column2'))

        for group in grouped:
            writer.writerows(group)

2 个答案:

答案 0 :(得分:2)

我不确定您是否完全需要在此处压缩。只需遍历输入文件的每一行,跳过空行,按句点分隔并写入csv文件即可:

import csv


with open('Abiutxt.txt', 'r') as in_file:
    with open('logtestAbiutxt.csv', 'w') as out_file:
        writer = csv.writer(out_file, delimiter="\t")
        writer.writerow(['Column1', 'Column2'])

        for line in in_file:
            if not line.strip():
                continue

            writer.writerow(line.strip().split(". ", 1))

注意:

  • 注意:已指定制表符作为分隔符,但您可以对其进行适当的更改
  • 感谢@PatrickHaugh提出将想法按". "的第一次出现来拆分的想法,因为第二列也可能包含句点。

答案 1 :(得分:0)

这应该为您提供所需的东西。这将处理所有转义。

import csv
with open('Abiutxt.txt', 'r') as in_file:
    x = in_file.read().splitlines()
    x = [line.split('. ', 1) for line in x if line]
with open('logtestAbiutxt.csv', "w") as output:
    writer = csv.writer(output, lineterminator='\n')
    writer.writerow(['Column1', 'Column2']) 
    writer.writerows(x)