18

我正在尝试解析一系列文本文件并使用 Python (2.7.3) 将它们保存为 CSV 文件。所有文本文件都有一个 4 行长的标题,需要去掉。数据行有各种分隔符,包括 "(引号)、-(破折号)、: 列和空格。我发现在 C++ 中使用所有这些不同的分隔符对其进行编码很痛苦,所以我决定在 Python 中尝试一下与 C/C++ 相比,做起来相对容易。

我写了一段代码来测试它的单行数据,它可以工作,但是,我无法让它对实际文件工作。为了解析单行,我使用了文本对象和“替换”方法。看起来我当前的实现将文本文件作为列表读取,并且列表对象没有替换方法。

作为 Python 的新手,我被困在了这一点上。任何输入将不胜感激!

谢谢!

# function for parsing the data
def data_parser(text, dic):
for i, j in dic.iteritems():
    text = text.replace(i,j)
return text

# open input/output files

inputfile = open('test.dat')
outputfile = open('test.csv', 'w')

my_text = inputfile.readlines()[4:] #reads to whole text file, skipping first 4 lines


# sample text string, just for demonstration to let you know how the data looks like
# my_text = '"2012-06-23 03:09:13.23",4323584,-1.911224,-0.4657288,-0.1166382,-0.24823,0.256485,"NAN",-0.3489428,-0.130449,-0.2440527,-0.2942413,0.04944348,0.4337797,-1.105218,-1.201882,-0.5962594,-0.586636'

# dictionary definition 0-, 1- etc. are there to parse the date block delimited with dashes, and make sure the negative numbers are not effected
reps = {'"NAN"':'NAN', '"':'', '0-':'0,','1-':'1,','2-':'2,','3-':'3,','4-':'4,','5-':'5,','6-':'6,','7-':'7,','8-':'8,','9-':'9,', ' ':',', ':':',' }

txt = data_parser(my_text, reps)
outputfile.writelines(txt)

inputfile.close()
outputfile.close()
4

3 回答 3

18

我会使用for循环来遍历文本文件中的行:

for line in my_text:
    outputfile.writelines(data_parser(line, reps))

如果您想逐行读取文件而不是在脚本开头加载整个内容,您可以执行以下操作:

inputfile = open('test.dat')
outputfile = open('test.csv', 'w')

# sample text string, just for demonstration to let you know how the data looks like
# my_text = '"2012-06-23 03:09:13.23",4323584,-1.911224,-0.4657288,-0.1166382,-0.24823,0.256485,"NAN",-0.3489428,-0.130449,-0.2440527,-0.2942413,0.04944348,0.4337797,-1.105218,-1.201882,-0.5962594,-0.586636'

# dictionary definition 0-, 1- etc. are there to parse the date block delimited with dashes, and make sure the negative numbers are not effected
reps = {'"NAN"':'NAN', '"':'', '0-':'0,','1-':'1,','2-':'2,','3-':'3,','4-':'4,','5-':'5,','6-':'6,','7-':'7,','8-':'8,','9-':'9,', ' ':',', ':':',' }

for i in range(4): inputfile.next() # skip first four lines
for line in inputfile:
    outputfile.writelines(data_parser(line, reps))

inputfile.close()
outputfile.close()
于 2012-08-13T15:03:49.850 回答
11

从接受的答案看来,您想要的行为是转身

skip 0
skip 1
skip 2
skip 3
"2012-06-23 03:09:13.23",4323584,-1.911224,-0.4657288,-0.1166382,-0.24823,0.256485,"NAN",-0.3489428,-0.130449,-0.2440527,-0.2942413,0.04944348,0.4337797,-1.105218,-1.201882,-0.5962594,-0.586636

进入

2012,06,23,03,09,13.23,4323584,-1.911224,-0.4657288,-0.1166382,-0.24823,0.256485,NAN,-0.3489428,-0.130449,-0.2440527,-0.2942413,0.04944348,0.4337797,-1.105218,-1.201882,-0.5962594,-0.586636

如果那是正确的,那么我认为类似

import csv

with open("test.dat", "rb") as infile, open("test.csv", "wb") as outfile:
    reader = csv.reader(infile)
    writer = csv.writer(outfile, quoting=False)
    for i, line in enumerate(reader):
        if i < 4: continue
        date = line[0].split()
        day = date[0].split('-')
        time = date[1].split(':')
        newline = day + time + line[1:]
        writer.writerow(newline)

会比reps东西简单一点。

于 2012-08-13T15:24:40.987 回答
2

有几种方法可以解决这个问题。一种选择是使用inputfile.read()而不是inputfile.readlines()- 您需要编写单独的代码来去除前四行,但如果您希望最终输出为单个字符串,这可能是最有意义的。

第二个更简单的选择是在用 . 分割前四行后重新加入字符串my_text = ''.join(my_text)。这有点低效,但如果速度不是主要问题,代码将是最简单的。

最后,如果您确实希望将输出作为字符串列表而不是单个字符串,则只需修改数据解析器以遍历列表即可。这可能看起来像这样:

def data_parser(lines, dic):
    for i, j in dic.iteritems():
        for (k, line) in enumerate(lines):
            lines[k] = line.replace(i, j)
    return lines
于 2012-08-13T15:11:08.527 回答