如何用Python从结构化文件数据中提取各月份数据生成独立列表?
实现方案
假设你已经把文件内容读取并拆分成了一个名为data_list的列表,示例格式大概是这样:
data_list = ["2024", "January", "31", "销售:1200", "库存:300", "February", "29", "销售:1500", "库存:250", "March", "31", "销售:1300"]
核心思路
- 遍历列表,用
str.isalpha()识别月份名称(因为只有月份名是纯字母格式) - 记录每个月份的起始位置,提取后续的天数和对应数据,直到遇到下一个月份或列表结束
- 把每个月份的数据整理成独立列表,用字典存储方便后续调用
代码实现
# 替换成你实际读取拆分后的列表 data_list = ["2024", "January", "31", "销售:1200", "库存:300", "February", "29", "销售:1500", "库存:250", "March", "31", "销售:1300"] monthly_data = {} current_month = None current_data = [] for item in data_list: # 跳过开头的年份(判断4位数字,格式不同可自行调整) if item.isdigit() and len(item) == 4: continue # 识别到新月份时,先保存上一个月份的数据 if item.isalpha(): if current_month is not None: monthly_data[current_month] = current_data current_month = item current_data = [] # 非月份内容,直接加入当前月份的列表 else: if current_month is not None: current_data.append(item) # 处理最后一个月份的剩余数据 if current_month is not None: monthly_data[current_month] = current_data # 查看结果 for month, data in monthly_data.items(): print(f"* {month}: {data}")
补充说明
- 运行后每个月份对应的列表会包含当月天数和所有相关数据,比如
January对应["31", "销售:1200", "库存:300"] - 如果数据里有其他纯字母的非月份内容,可以额外加一层判断(比如和已知月份列表比对),但如果只有月份是纯字母,当前方案完全适用
- 用字典存储的好处是后续可以直接通过
monthly_data["January"]快速调取对应月份的数据
内容的提问来源于stack exchange,提问作者John Smith
相关产品推荐
相关产品推荐

