首页 > 解决方案 > 如何读取特定行,然后将其添加到字典 python

问题描述

我有这样的文件,我想从一行by walk到一行读取它car,然后将它添加到字典中,其中 key 是 time 7.00 - 8.00, value 是 number 150

例如

by_walk = {"7.00 - 8.00":150, "8.00 - 9.00":175 and et cetera}
car = {"7.00 - 8.00":150, "8.00 - 9.00":175 and et cetera}
bus = {"7.00 - 8.00":150, "8.00 - 9.00":175 and et cetera}

我怎样才能做到这一点?

By walk
7.00 - 8.00 - 150
8.00 - 9.00 - 175
9.00 - 10.00 - 120
10.00 - 11.00 - 30
11.00 - 12.00 - 10
12.00 - 13.00 - 10
13.00 - 14.00 - 10
14.00 - 15.00 - 10
15.00 - 16.00 - 10
16.00 - 17.00 - 175
17.00 - 18.00 - 150
18.00 - 19.00 - 50
Car
7.00 - 8.00 - 150
8.00 - 9.00 - 175
9.00 - 10.00 - 120
10.00 - 11.00 - 30
11.00 - 12.00 - 10
12.00 - 13.00 - 10
13.00 - 14.00 - 10
14.00 - 15.00 - 10
15.00 - 16.00 - 10
16.00 - 17.00 - 175
17.00 - 18.00 - 150
18.00 - 19.00 - 50
Bus
7.00 - 8.00 - 150
8.00 - 9.00 - 175
9.00 - 10.00 - 120
10.00 - 11.00 - 30
11.00 - 12.00 - 10
12.00 - 13.00 - 10
13.00 - 14.00 - 10
14.00 - 15.00 - 10
15.00 - 16.00 - 10
16.00 - 17.00 - 175
17.00 - 18.00 - 150
18.00 - 19.00 - 50

感谢所有答案,我有一个问题,我不知道如何读取从汽车到公共汽车的线路,这是我的代码:

 by_walk = {}
 car = {}
 bus = {}
 for line in open("test.txt"):
     if line.strip() != "Car":
         if line.strip() == "By walk":
             continue
         line = line.rsplit('-', 1)
         by_walk[line[0].strip()] = int(line[1])
     elif line.strip() == "Car":
          break
for line in open("test.txt"):

但是在第一个循环之后,我不知道该做什么以及我需要编写什么代码。

标签: pythonlistdictionary

解决方案


在:

import re

dict1 = dict()
readValues = iter(re.split('\n', open("file.txt", "r").read()))
next(readValues)
for v in readValues:
    rV = re.split("(([0-9- ]{1,2}.[0-9- ]{1,2}) - ([0-9- ]{1,2}.[0-9- ]{1,2})\w+)", v)
    dict1[rV[1]] = rV[4].replace("-", "").strip()

print(dict1)

出去:

 {'7.00 - 8.00': '150', '8.00 - 9.00': '175', '9.00 - 10.00': '120', '10.00 - 11.00': '30', '11.00 - 12.00': '10', '12.00 - 13.00': '10', '13.00 - 14.00': '10', '14.00 - 15.00': '10', '15.00 - 16.00': '10', '16.00 - 17.00': '175', '17.00 - 18.00': '150', '18.00 - 19.00': '50'}

推荐阅读