如何使用python将文本文件转换为csv

2024-05-13 21:27:16 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个要求,在那里我需要把我的文本文件转换成csv,并使用python来做这件事。我的文本文件是这样的

1. Which of the following structure are made of several layer's of cells :-
(A) Ciliated epithelium (B) Stratified epithelium
(C) Cuboidal epithelium (D) Columnar epithelium
2. Which simple epithelium tissue cells are square in vertical sections and Polygonal in horizontal section
(A) Columnar epithelium (B) Squamous epithelium
(C) Cuboidal epithelium (D) Ciliated epithelium

我想要一个CSV,如下所示:

1, "Which of the following structure are made of several layer's of cells :-", "Ciliated epithelium", "Stratified epithelium", "Cuboidal epithelium", "Columnar epithelium"
2, "Which simple epithelium tissue cells are square in vertical sections and Polygonal in horizontal section", "Columnar epithelium", "Squamous epithelium", "Cuboidal epithelium", "Ciliated epithelium"

我试过多种方法,但都没有成功。有什么办法解决这个问题吗?提前谢谢。你知道吗


Tags: oftheinwhichstructurearefollowing文本文件
2条回答

下面是一个基于示例输入的分步示例:

#!python3
import csv

# Open the original file as reading text (the default.
# Open the output file per csv documentation for csv.writer use.
with open('original.txt') as fin,open('out.csv','w',newline='') as fout:
    # Read the lines stripping leading and trailing whitespace.
    lines = [line.strip() for line in fin]
    # Set up the csv writer to quote the text fields.
    w = csv.writer(fout,quoting=csv.QUOTE_NONNUMERIC)
    # Make sure the input file has multiples of three lines.     
    if len(lines) % 3 != 0:
        raise RuntimeError('expected multiples of 3 lines')
    # Index through the lines 3-at-a-time.
    for i in range(0,len(lines),3):
        # Break apart lines and assign to columns.
        # Make sure col1 is a numeric field so it won't get quoted.
        tmp,col2 = lines[i].split('. ')
        col1 = int(tmp)
        col3,col4 = lines[i+1][4:].split(' (B) ')
        col5,col6 = lines[i+2][4:].split(' (D) ')
        w.writerow([col1,col2,col3,col4,col5,col6])

输出:

1,"Which of the following structure are made of several layer's of cells :-","Ciliated epithelium","Stratified epithelium","Cuboidal epithelium","Columnar epithelium"
2,"Which simple epithelium tissue cells are square in vertical sections and Polygonal in horizontal section","Columnar epithelium","Squamous epithelium","Cuboidal epithelium","Ciliated epithelium"

试试这个代码!你知道吗

我还附加了csv文件的输出。你知道吗

import csv

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

enter image description here

相关问题 更多 >