python - 如何读取特定行,然后将其添加到字典 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"):
但是在第一个循环之后,我不知道该做什么以及我需要编写什么代码。
解决方案
在:
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'}
推荐阅读
- python - 如何在不添加到图形的情况下将张量对象转换为数组?
- terraform - Terragrunt:提供程序“tfstate”不可安装
- powershell - Powershell Get-Content,使用 ARRAY 过滤,然后设置内容
- python - Jupyter Notebook 中没有显示名称和 $DISPLAY 环境变量
- r - 对按日期排序的同一组中的连续值求和
- r - 如何让 X & Y 行匹配?
- mysql - SQL 从最大值中选择 ID
- jquery - 在最后一个 UL 中动态填充 LI
- java - 如何在 EditText 中添加所有单个整数?
- python - 符号学插值;从 y 中得到 x