0

我有一个想要更改的 txt 文件,因此我可以将数据放入列中,请参见下面的示例。这背后的原因是我可以将这些数据导入数据库/数组并对其执行计算。我尝试将数据导入/粘贴到 LibreCalc 中,但它只是将所有内容导入一列,或者在 LibreWriter 中打开文件,我使用的是 ubuntu 10.04。有任何想法吗?我愿意使用另一个程序来解决这个问题。我也可以使用逗号分隔的文件,但我不确定如何将数据自动转换为该格式。

Trying to get this:
WAVELENGTH,   WAVENUMBER,   INTENSITY,    CLASSIFICATION,     CODE,
1132.8322,    88274.326,     2300,        PT II,   9356- 97630,       05,

这是完整文件的链接。 pt.txt 文件

4

4 回答 4

2

尝试这个:

sed -e "s/(\s+)/,$1/g" pt.txt
于 2011-10-20T08:32:29.083 回答
1

这是你想要的吗?

awk 'BEGIN{OFS=","}NF>1{$1=$1;print}' pt.txt

如果你想让输出格式看起来更好,并且你已经安装了“列”,你也可以试试这个:

awk 'BEGIN{OFS=", "}NF>1{$1=$1;print}' pt.txt|column -t
于 2011-10-20T08:22:51.133 回答
0

The easiest way turned out to be importing using a fixed width like tohuwawohu suggested Thanks

Without transforming it to a comma-separated file, you could access the csv import options by simply changing the file extension to .csv (maybe you should remove the "header" part manually, so that only the columns heads and the data rows do remain). After that, you can try to use whitespace as column delimiter, or even easier: select "fixed width" and set the columns manually. – tohuwawohu Oct 20 at 9:23

于 2011-10-23T21:04:34.290 回答
0

和one-liners 很酷awksed但我希望您最终需要做的不仅仅是拆分文件。如果你这样做了,并且你可以访问 Python 2.7,那么下面的小脚本会让你继续前进。

# -*- coding: utf-8 -*-

"""Convert to comma-delimited"""

import csv
from os import path
import re
import sys


def splitline(line):
    return re.split('\s{2,}', line)


def main():
    srcpath = path.abspath(sys.argv[1])
    targetpath = path.splitext(srcpath)[0] + '.csv'

    with open(srcpath) as infile, open(targetpath, 'w') as outfile:
        writer = csv.writer(outfile)
        for line in infile:
            if line.startswith('  '):
                line = line.strip()
                cols = splitline(line)
                writer.writerow(cols)


if __name__ == '__main__':
    main()
于 2011-10-20T09:11:35.550 回答