簡體   English   中英

讀取文本文件並在python中解析

[英]Read text file and parse in python

我有一個文本文件(.txt)如下所示:


日期,日期,宗派,1、2、3

1,太陽,1-1,123,345,678

2,星期一,2-2,234,585,282

3,星期二,2-2,231,232,686


使用此數據,我想執行以下操作:

1)作為列表中的單獨元素逐行讀取文本文件

  • 用逗號分割元素

  • 刪除列表中不必要的元素('\\ n')

對於這兩個,我做了這些。

file = open('abc.txt', mode = 'r', encoding = 'utf-8-sig')
lines = file.readlines()
file.close()
my_dict = {}
my_list = []
for line in lines:
    line = line.split(',')
    line = [i.strip() for i in line]

2)將第一行(日期,日期,日期,1、2、3)設置為鍵,並將其他行設置為字典中的值。

    my_dict['Date'] = line[0]
    my_dict['Day'] = line[1]
    my_dict['Sect'] = line[2]
    my_dict['1'] = line[3]
    my_dict['2'] = line[4]
    my_dict['3'] = line[5]

上面的代碼有兩個問題:1)還將第一行設置為字典。 2)如果我將其添加到列表中,如下所示,它將僅保留最后一行作為列表中的所有元素。

3)創建一個包含字典作為元素的列表。

    my_list.append(my_dict)    

4)細分我想要的元素。

我無法從此處編寫任何代碼。 但是我要做的是滿足條件的子集元素:例如,在Sect為2-2的字典中選擇元素。 然后,所需結果可能如下:

>> [{'Date': '2', 'Day': 'Mon', 'Sect': '2-2', '1': '234', '2': '585', '3': '282'}, {'Date': '3', 'Day': 'Tue', 'Sect': '2-2', '1': '231', '2':'232', '3':'686'}]

謝謝,

@ supremed14 ,您也可以在閱讀文件后嘗試以下代碼來准備字典列表。

data.txt中

文本文件中有空格。 在字符串上定義的strip()方法將解決此問題。

Date, Day, Sect, 1, 2, 3

1, Sun, 1-1, 123, 345, 678

2, Mon, 2-2, 234, 585, 282

3, Tue, 2-2, 231, 232, 686

源代碼:

在這里,您不必擔心關閉文件。 Python會注意的。

import json
my_list = [];

with open('data.txt') as f:
    lines = f.readlines() # list containing lines of file
    columns = [] # To store column names

    i = 1
    for line in lines:
        line = line.strip() # remove leading/trailing white spaces
        if line:
            if i == 1:
                columns = [item.strip() for item in line.split(',')]
                i = i + 1
            else:
                d = {} # dictionary to store file data (each line)
                data = [item.strip() for item in line.split(',')]
                for index, elem in enumerate(data):
                    d[columns[index]] = data[index]

                my_list.append(d) # append dictionary to list

# pretty printing list of dictionaries
print(json.dumps(my_list, indent=4))

輸出:

[
    {
        "Date": "1",
        "Day": "Sun",
        "Sect": "1-1",
        "1": "123",
        "2": "345",
        "3": "678"
    },
    {
        "Date": "2",
        "Day": "Mon",
        "Sect": "2-2",
        "1": "234",
        "2": "585",
        "3": "282"
    },
    {
        "Date": "3",
        "Day": "Tue",
        "Sect": "2-2",
        "1": "231",
        "2": "232",
        "3": "686"
    }
]

使用熊貓很簡單:

輸入:

$cat test.txt
Date, Day, Sect, 1, 2, 3
1, Sun, 1-1, 123, 345, 678
2, Mon, 2-2, 234, 585, 282
3, Tue, 2-2, 231, 232, 686

操作:

import pandas as pd
df = pd.read_csv('test.txt', skipinitialspace=True)
df.loc[df['Sect'] == '2-2'].to_dict(orient='records')

輸出:

[{'1': 234, '2': 585, '3': 282, 'Date': 2, 'Day': 'Mon', 'Sect': '2-2'},
 {'1': 231, '2': 232, '3': 686, 'Date': 3, 'Day': 'Tue', 'Sect': '2-2'}]

如果您的.txt文件為CSV格式:

Date, Day, Sect, 1, 2, 3

1, Sun, 1-1, 123, 345, 678

2, Mon, 2-2, 234, 585, 282

3, Tue, 2-2, 231, 232, 686

您可以使用csv庫:

from csv import reader
from pprint import pprint

result = []
with open('file.txt') as in_file:

    # create a csv reader object
    csv_reader = reader(in_file)

    # extract headers
    headers = [x.strip() for x in next(csv_reader)]

    # go over each line 
    for line in csv_reader:

        # if line is not empty
        if line:

            # create dict for line
            d = dict(zip(headers, map(str.strip, line)))

            # append dict if it matches your condition
            if d['Sect'] == '2-2':
                result.append(d)

pprint(result)

給出以下列表:

[{'1': '234', '2': '585', '3': '282', 'Date': '2', 'Day': 'Mon', 'Sect': '2-2'},
 {'1': '231', '2': '232', '3': '686', 'Date': '3', 'Day': 'Tue', 'Sect': '2-2'}]

我建議您將文件設為.csv(逗號分隔值)文件,該文件的解析器應如下所示

def parseCsvFile (dataFile):
    dict = {}
    with open(dataFile) as csvfile:
        reader = csv.DictReader(csvfile)
        for row in reader:
            key = None
            for k in row:
                stripK = k.strip()
                stripV = row[k].strip()
                if key == None:
                    key = stripV
                    dict[key] = {}
                dict[key][stripK] = stripV
    return dict

這將返回詞典字典

如果允許使用pandas ,則可以通過以下方式簡單地完成任務:

import pandas as pd
df = pd.read_csv('abc.txt', skipinitialspace=True) # reads your cvs file into a DataFrame
d = df.loc[df['Sect'] == '2-2'].to_dict('records') # filters the records which `Sect` value is '2-2', and returns a list of dictionaries

要安裝pandas運行:

python3 -m pip install pandas

假設abc.txt的內容就是您提供的內容,則d為:

[{'Date': 2, 'Day': 'Mon', 'Sect': '2-2', '1': 234, '2': 585, '3': 282},
 {'Date': 3, 'Day': 'Tue', 'Sect': '2-2', '1': 231, '2': 232, '3': 686}]

暫無
暫無

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

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