gpt4 book ai didi

python - 如何将此文本文件格式解析为 CSV 格式?

转载 作者:行者123 更新时间:2023-12-02 06:40:29 25 4
gpt4 key购买 nike

我有一个这样布局的文本文件,其中每个字段都是一个新行:

id = 606149
Category Name = Structural Columns
Family Name = Concrete-Square-Column
Type Name = EXIST RH C1 16 x 16
Document = 15050 Peavy Struct v2016_detached
Attachment Justification At Top = Minimum Intersection
Image = <None>
Offset From Attachment At Top = 0
id = 606151
Category Name = Structural Columns
Family Name = Concrete-Square-Column
Type Name = EXIST RH C2 16 x 16
Document = 15050 Peavy Struct v2016_detached
Attachment Justification At Top = Minimum Intersection
Image = <None>
Offset From Attachment At Top = 0

在我的代码中,我打开文本文件进行读取并打印出前三行进行测试。当我尝试在行尾添加逗号时,我在下面的行中得到了逗号:

def main():
count = 0
filename = "test.txt"
file = open(filename, "r")
for line in file:
if count == 3:
break
count = count + 1
line += ','
print line

使用这段代码我得到结果:

id = 606149
,
Category Name = Structural Columns
,
Family Name = Concrete-Square-Column
,

当我在连接逗号之前添加线带以去除新行时:

line = line.strip('\n')"

我得到这个结果:

,id = 606149
,ategory Name = Structural Columns
,amily Name = Concrete-Square-Column

我无法将此文件解析为 CSV 格式。

最佳答案

你可以这样做来获得想要的o/p,但是你必须提到这一点:

with open('j.txt', 'r') as f:
d =f.readlines()
for i in d:
i = i.rstrip('\n')
i+=','
print(i)

我在这里使用了 rstrip ,它将打印所有行,对于前三行,您可以给出一些循环或条件。O/P 是这样的:

id = 606149, Category Name = Structural Columns, Family Name = Concrete-Square-Column, Type Name = EXIST RH C1 16 x 16, Document = 15050 Peavy Struct v2016_detached,
Attachment Justification, At Top = Minimum Intersection, Image = Offset From Attachment At Top = 0,

关于python - 如何将此文本文件格式解析为 CSV 格式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48537209/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com