设计思路
- 逐行读取大文本文件,避免一次性将整个文件读入内存。
- 使用Python字典来统计每种
event_type
下不同user_id
出现的次数。外层字典的键为event_type
,内层字典的键为user_id
,值为出现次数。
- 为了优化性能,在读取文件时可以使用
with open
语句来确保文件正确关闭,并且在处理JSON数据时,使用json.loads
方法。
核心代码
import json
result = {}
with open('large_text_file.txt', 'r') as file:
for line in file:
try:
data = json.loads(line)
event_type = data.get('event_type')
user_id = data.get('user_id')
if event_type and user_id:
if event_type not in result:
result[event_type] = {}
if user_id not in result[event_type]:
result[event_type][user_id] = 1
else:
result[event_type][user_id] += 1
except json.JSONDecodeError:
continue
print(result)