簡體   English   中英

在Python中將雜亂的數據文件清理為更具可讀性的格式?

[英]Cleaning up a messy data file to a more readable format in Python?

我有一個文本文件(在此示例中進行了大幅修改),其中包含一些我要提取的數據並對其進行一些計算。 但是,文本文件非常混亂,因此我試圖對其進行清理,然后將其首先寫到新文件中。

這是我正在使用的.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之間的所有混亂信息。

關於如何讀取標題下的所有數據並將其輸出到單獨文件的任何建議? 謝謝你的時間。

您可以使用正則表達式。

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 = ''

我不知道您要如何存儲數據,但是假設您要使用字典,可以使用正則表達式檢查傳入的行是否與模式匹配,然后由於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

另一個正則表達式解決方案:

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)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM