【发布时间】:2019-10-22 09:32:53
【问题描述】:
考虑以下文本文件摘录
Distance,Velocity,Time
(m),(m/s),(s)
1,1,1
2,1,2
3,1,3
我希望它变成这样:
Distance(m),Velocity(m/s),Time(s)
1,1,1
2,1,2
3,1,3
换句话说,我想连接包含文本的行,并且我希望它们按列连接。
我最初是在处理从软件生成的文本文件。我已成功地将其转换为 csv 格式的数字列及其标题。但我每列都有多个标题。而且我需要每个标题行中的所有信息,因为列属性因文件而异。我怎样才能在 python 中以一种聪明的方式做到这一点?
edit:谢谢你的建议,对我帮助很大。我使用了 Daweos 解决方案,并添加了动态行数,因为标题行的数量可能从 2 到 7 不等,具体取决于生成的输出。这是我最终得到的代码 sn-p。
# Get column headers
a = 0
header_rows= 0
with open(full,"r") as input:
Lines= ""
for line in input:
l = line
g = re.sub(' +',' ',l)
y = re.sub('\t',',',g)
numlines += 1
if len(l.encode('ANSI')) > 250:
# finds header start row
a += 1
if a>0:
# finds header end row
if "---" in line:
header_rows = numlines - (numlines-a+1)
break
else:
# Lines is my headers string
Lines = Lines + "%s" % (y) + ' '
output.close()
# Create concatenated column headers
rows = [i.split(',') for i in Lines.rstrip().split('\n')]
cols = [list(c) for c in zip(*rows)]
for i in (cols):
for j in (rows):
newcolz = [list(c) for c in zip(*rows)]
print(newcolz)
【问题讨论】:
-
到目前为止你尝试了什么?
-
您好,请查看已编辑的帖子。
标签: python string csv concatenation