在Python中将凌乱的数据文件清理为更易读的格式?

时间:2016-07-22 15:30:48

标签: python file-io

我有一个文本文件(对于此示例进行了大量修改),其中包含一些我想要提取的数据并使用它进行一些计算。然而,文本文件非常混乱,所以我试图将其清理并首先将其写入新文件。

以下是我正在使用的.txt文件:http://textuploader.com/5elql

我正在尝试提取标题下的数据(称为“重要标题”)。唯一可能的方法是首先找到一个总是出现在文件中的字符串,并将其称为“DATASET”,因为重要数据上方和下方的所有混乱都将覆盖任意数量的行,难以手动删除。一旦完成,我想将数据存储在单独的文件中,以便更容易分析:

http://textuploader.com/5elqw

文件名将与标题+日期连接。

这是我到目前为止所尝试的内容

with open("example.txt") as file:
    for line in file:
        if line.startswith('DATASET:'):
            fileTitle = line[9:]
        if line.startswith("DATE:"):
            fileDate = line[:]
            print(fileTitle+fileDate)

输出

IMPORTANT TITLE 1
DATE: 12/30/2015

IMPORTANT TITLE 2
DATE: 01/03/2016

所以看来我的循环设法找到文件里面标题的行并打印出来。但这是我失去动力的地方。我不知道如何从那里开始提取这些标题下的数据。我尝试过使用file.readlines()但它输出了重要标题1和重要标题2之间的所有混乱。

有关如何阅读标题下的所有数据并将其输出到单独文件中的任何建议?谢谢你的时间。

3 个答案:

答案 0 :(得分:1)

你可以使用正则表达式。

import re

pattern = r"(\s+X\s+Y\s*)|(\s*\d+\s+\d+\s*)"
prog = re.compile(pattern)

with open("example.txt") as file:
cur_filename = ''
content = ""
for line in file:
    if line.startswith('DATASET:'):
        fileTitle = line[9:]
    elif line.startswith("DATE:"):
        fileDate = line[6:]
        cur_filename = (fileTitle.strip() + fileDate.strip()).replace('/', '-')
        print(cur_filename)
        content_title = fileTitle + line
    elif prog.match(line):
        content += line
    elif cur_filename and content:
        with open(cur_filename, 'w') as fp:
            fp.write(content_title)
            fp.write(content)
        cur_filename = ''
        content = ''

答案 1 :(得分:0)

我不知道您想要如何存储数据,但假设您需要字典,可以使用正则表达式检查传入行是否与模式匹配,那么因为fileTitle不是全局的,您可以使用那作为关键并添加值。我还添加了rstrip('\r\n')以删除fileTitle之后的换行符。

import re

#if you don't want to store the X and Y, just use re.compile('\d\s+\d+')
p = re.compile('(\d\s+\d+)|(X\s+Y)')
data={}
with open("input.txt") as file:
    for line in file:
        if line.startswith('DATASET:'):
            fileTitle = line[9:].rstrip('\r\n')
        if line.startswith("DATE:"):
            fileDate = line[:]
            print(fileTitle+fileDate)
        if p.match(line):
            if fileTitle not in data:
                data[fileTitle]=[]
            line=line.rstrip('\r\n')
            data[fileTitle].append(line.split('\t'))
            if len(data[fileTitle][len(data[fileTitle])-1]) == 3:
                data[fileTitle][len(data[fileTitle])-1].pop()

print data

答案 2 :(得分:0)

又一个正则表达式解决方案:

sep = '*************************\n'

pattern = r'DATASET[^%]*'
good_stuff = re.compile(pattern)
pattern = r'^DATASET: (.*?)$'
title = re.compile(pattern, flags = re.MULTILINE)
pattern = r'^DATE: (.*?)$'
date = re.compile(pattern, flags = re.MULTILINE)

with open(r'foo.txt') as f:
    data = f.read()
for match in good_stuff.finditer(data):
    data = match.group()
    important_title = title.search(data).group(1)
    important_date = date.search(data).group(1)
    important_date = important_date.replace(r'/', '-')
    fname = important_title + important_date + '.txt'
    print(sep, fname)
    print(data)
    ##with open(fname, 'w') as f:
    ##    f.write(data)