如何读取文本文件并将其中的数据放入Python字典中?

问题描述 投票:0回答:1

在如下文本文件中的数据中,日期作为键,小数值(1.85等)作为数据应放入Python字典中。

文本文件(mytext.txt)

BBM **17/12/2023 15:15:04** *1.85* 2700.0 41857.9                                                                         
BBM **17/12/2023 16:00:02** *1.68* 2698.0 41992.8                                                                 
BBM **17/12/2023 16:45:04** *1.6* 2702.0 41908.3                                                         
BBM **17/12/2023 17:30:10** *1.47* 2706.0 41975.1                                                                                                    
BBM **17/12/2023 18:15:02** *1.35* 2692.0 41934.5                                                                                         

读完上面的文本文件后,我的字典应该是这样的。

myDict = {
    '17/12/2023 15:15:04': 1.85,
    '17/12/2023 16:00:02': 1.68,
    '17/12/2023 16:45:04': 1.6,
    '17/12/2023 17:30:10': 1.47,
    '17/12/2023 18:15:02': 1.35
}

我尝试了多种方法,但都不起作用。

python python-3.x dictionary text file-read
1个回答
0
投票

我认为你可以这样做:

myDict = {}

with open('mytext.txt', 'r') as file:
    for line in file:
        words = line.split()
        if len(words) >= 3:
            if len(words[1].split('/')) == 3 and len(words[2]) > 0 and words[2][0].isdigit():
                date_time = ' '.join([words[1], words[2]])
                myDict[date_time] = float(words[3])

print(myDict)

我现在无法尝试读取文件,但是当我直接将文本放入变量中时,算法本身对我有用。

© www.soinside.com 2019 - 2024. All rights reserved.