使用Python重新排列.txt行和列

时间:2017-05-07 14:27:16

标签: python text rows

我是一名新手编码员,需要帮助组合和重新排列大量的.txt数据。我有500个文本文件(实际上有.pts文件,但这似乎与.txt相同),面部地标坐标是从使用CLM Facetracker的人的照片中提取的。每张照片的输出都是这样的(68行向下):

版本:1

n点:68 {

216.512 146.425

217.526 166.783

219.63 187.059

(....)

}

相当于:

X1,Y1

X2,Y2

我希望重新排列它,所以所有68个地标坐标都在一行中,每个坐标之间都有一个逗号:

216.512,146.425,217.526,166.783,219.63,187.059

x1,y1,x2,y2

有一种简单的方法吗?理想情况下,我还想添加零,以便所有地标坐标具有相同的小数位数。在此先感谢,如果我遗漏了一些非常明显的东西,请道歉:)

3 个答案:

答案 0 :(得分:0)

# read the data from "in.txt"
data_list = open('in.txt','r').read().split()

# format to 3 decimal places
data_fmt = []
for dl in data_list:
    try:
        data_fmt.append("{0:.3f}".format(float(dl)))
    except:
        print repr('Could not convert "{}"'.format(dl))

# join the list with a comma
data_str = ','.join(data_fmt)

# write the output to a file
with open('out.txt','w') as fout:
    fout.write(data_str)

答案 1 :(得分:0)

with open(fileName, "r") as f:
    values = f.read().split()
print(", ".join(values))

如果您想要一定数量的小数位,请说4:

with open(filename, "r") as f:
    values = map(float, f.read().split())

s = []
for v in values:
    s.append("{:.4f}".format(v))

print(", ".join(s))

答案 2 :(得分:0)

  1. 读取文件
  2. 读取行
  3. 用分隔符替换空格
  4. 删除行尾(换行符和/或换行符)
  5. 添加到新字符串
  6. 将结果字符串写入新文件
  7. 尝试让它工作(未经测试):

    newline = ""
    with open("filename.pts", "r") as f: # 1
        for line in f: # 2
            line = line.replace(" ", ", ") # 3
            line = line.strip() # 4
            newline += line # 5
    
    with open("newfilename.pts", "w") as f: # 6
        f.write(newline)
    
    print("done!")
    

    一些文档: https://docs.python.org/3.4/library/functions.html#open https://docs.python.org/3/library/stdtypes.html#string-methods

    这可以写得更紧凑,例如请看@ Nik的答案。

    使用文本编辑器的搜索和替换功能,支持特殊字符(空格,cr,lf)。 Notepad++可以做到,Atom也可以(还有很多其他人)。