csv 在python中处理文本文件-复制垂直文本并水平粘贴

q3aa0525  于 2023-03-15  发布在  Python
关注(0)|答案(1)|浏览(196)

如何复制垂直文本并将其水平粘贴为csv格式。

input_text_file = """
Statement 1
some text
some text
some text
some text
some text
some text
some text
Statement 2
some text
some text
some text
some text
some text
some text
Statement 3
some text
some text
some text
some text
some text
some text
some text
some text
some text
some text
some text
Statement 4
some text
some text
some text
some text
some text
some text
some text
some text
...........
"""

检查该行是否以 Statement 开头,将所有内容复制到以 Statement 开头的下一行,并将其水平粘贴为csv(逗号分隔)。
并非所有语句的行数都相同。

with open('input_text_file', 'r') as intext:
    for line in intext:
        if line.startwith('Statement'):
            continue till the next line.startwith('Statement')
            ..........

with open('output_csv_file', 'w') as csvfile:
    write to csv file

output_csv_file ="""
Statement 1,Statement 2,Statement 3,Statement 4
some text  ,some text  ,some text  ,some text  
some text  ,some text  ,some text  ,some text  
some text  ,some text  ,some text  ,some text  
some text  ,some text  ,some text  ,some text  
some text  ,some text  ,some text  ,some text  
some text  ,some text  ,some text  ,some text  
some text              ,some text  ,some text
                       ,some text  ,some text
                       ,some text
                       ,some text
                       ,some text
"""

如何在python中实现这一点?

omqzjyyz

omqzjyyz1#

csv.writer使用以下迭代方法:

import csv

with StringIO(input_text_file) as f, open('result.csv', 'w') as out:
    d = {}

    for row in f:
        row = row.strip()
        if row:
            if row.startswith('Statement'):  # capture key/column name
                key = row
                d[key] = []
            else:
                d[key].append(row)
                
    writer = csv.writer(out)
    writer.writerow(d.keys())  # write header
    writer.writerows(zip(*d.values()))

result.csv内容物:

Statement 1,Statement 2,Statement 3,Statement 4
some text,some text,some text,some text
some text,some text,some text,some text
some text,some text,some text,some text
some text,some text,some text,some text
some text,some text,some text,some text
some text,some text,some text,some text

相关问题