python写代码 阅读以下题目,分别对应两个问题,实现以下功能: 下面所示为一套由海员随身佩戴的位置传感器采集的数据,其内容示例如下: 2016/5/31 0:05, vawelon001, 1, 1 2016/5/31 0:20, earpa001,3,4 2016/5/31 2:26, earpa001,2,1 2016/5/31 0:25, earpa002,4,2 2016/5/31 2:27, earpa004,5, 6 2016/5/31 0:09, vawelon002, 1, 1 2016/6/1 2:26, earpa003,7, 2 2016/6/13 7:26, earpa001,6,2 2016/6/31 10:05, vawelon002, 2, 1 第一列是传感器获取数据的时间,第二列是传感器的编号,第三列是传感器所在的位置区域编号,第四列是传感器所在的楼层。 用python创建的“info.txt”文件,并将给出的数据输入并写入新创建的文件中,之后提取出传感器编号为earpa00的所有数据,将结果输出保存到“earpa001. txt”文件。输出文件格式要求:原数据文件中的每行记录写入新文件中,行尾无空格,无空行。参考格式如下: 2016/5/31 7:11, earpa001,2, 4 2016/5/31 8:02, earpa001,3, 4 2016/5/31 9:22 earpa001,3,4 读入“earpa001. txt” 文件中的数据,统计earpa001对应的职员在各楼层和区域出现的次数,保存到“earpa001 _count. txt” 文件,每条记录一行,位置信息和出现的次数之间用英文半角逗号隔开,行尾无空格,无空行。参考格式如下。 2016/5/31 0:20-earpa001,3,4,1 2016/5/31 2:26-earpa001,2,1,1 2016/6/13 7:26-earpa001,6,2,1
时间: 2023-05-27 08:04:18 浏览: 95
问题一:
```python
# 将数据写入文件info.txt
with open('info.txt', 'w') as f:
data = """2016/5/31 0:05, vawelon001, 1, 1
2016/5/31 0:20, earpa001,3,4
2016/5/31 2:26, earpa001,2,1
2016/5/31 0:25, earpa002,4,2
2016/5/31 2:27, earpa004,5,6
2016/5/31 0:09, vawelon002,1,1
2016/6/1 2:26, earpa003,7,2
2016/6/13 7:26, earpa001,6,2
2016/6/31 10:05, vawelon002,2,1"""
f.write(data)
# 提取 earpa001 的数据并写入 earpa001.txt
with open('info.txt', 'r') as f:
lines = f.readlines()
with open('earpa001.txt', 'w') as f:
for line in lines:
if 'earpa001' in line:
f.write(line)
```
问题二:
```python
# 统计 earpa001 出现的次数
counter = {}
with open('earpa001.txt', 'r') as f:
lines = f.readlines()
for line in lines:
parts = line.strip().split(', ')
time, sensor, position, floor = parts
key = f"{time}-{sensor},{position},{floor}"
counter[key] = counter.get(key, 0) + 1
# 将结果写入 earpa001_count.txt
with open('earpa001_count.txt', 'w') as f:
for k, v in counter.items():
f.write(f"{k},{v}\n")
```
阅读全文