如何将特定格式字符串转换为list of lists或dict以存入Excel?
问题描述
我有一段带换行的文本内容,格式如下:
Name: Thompson shipping co. 17VXCS947 Name: Orange juice no pulp, Price: 7, Weight: 2, Aisle:9, Shelf_life: 30, 67 Name: Orange juice pulp, Price: 7, Weight:2, Aisle:9, Shelf_life:30, Photo is available, Photo is available, 56GHIO098 Name: Cranberry Juice, Price: 3, Weight: 1, Aisle:9, Shelf_life:45, Name: Lemonade, Price:1, Weight:1, Aisle:9, Shelf_life:10,
最终目标是把这些内容存入Excel,需要转换成列表的列表(示例格式如下)或字典:
[ ['Name: Thompson shipping co.'], ['Name: Orange juice no pulp', 'Price: 7', 'Weight: 2', 'Aisle:9', 'Shelf_life: 30'], ['Name: Orange juice pulp', 'Price: 7', 'Weight:2', 'Aisle:9', 'Shelf_life:30'], # ... 其他条目 ]
目前我用正则的re.findall逐个提取字段:
re.findall('(?<=,)[^,]*Name:[^,]*(?=,)'), re.findall('(?<=,)[^,]*Price:[^,]*(?=,)'), re.findall('(?<=,)[^,]*Weight:[^,]*(?=,)') # ... 其他字段
但第一个Name是单独一行的特殊情况,考虑过每5个结果分组存入新列表,但不够简洁,想找更优雅的实现方法。
解决方案
可以通过先过滤无效行,再用正则匹配完整记录的方式处理,一步到位提取所有目标条目:
步骤1:预处理文本,过滤无关行
先把文本按行拆分,过滤掉不含Name:、Price:等目标字段的行(比如纯编码、Photo is available这类行),只保留有效记录行。
步骤2:正则匹配每条记录
针对两种记录格式(单独的Name行、包含多字段的商品行),用统一的正则规则提取所有符合Key: Value格式的字段,直接整理成目标格式。
完整代码示例(列表的列表格式)
import re # 原始文本 text = """Name: Thompson shipping co. 17VXCS947 Name: Orange juice no pulp, Price: 7, Weight: 2, Aisle:9, Shelf_life: 30, 67 Name: Orange juice pulp, Price: 7, Weight:2, Aisle:9, Shelf_life:30, Photo is available, Photo is available, 56GHIO098 Name: Cranberry Juice, Price: 3, Weight: 1, Aisle:9, Shelf_life:45, Name: Lemonade, Price:1, Weight:1, Aisle:9, Shelf_life:10, """ # 1. 按行拆分并过滤无效行 lines = [line.strip().rstrip(',') for line in text.splitlines() if line.strip()] valid_lines = [line for line in lines if any(key in line for key in ['Name:', 'Price:', 'Weight:', 'Aisle:', 'Shelf_life:'])] # 2. 提取每条记录的字段,整理成列表的列表 result = [] for line in valid_lines: # 匹配所有"Key: Value"格式的字段 fields = [match.group(0) for match in re.finditer(r'(Name|Price|Weight|Aisle|Shelf_life):\s*[^,]+', line)] result.append(fields) # 输出结果 print(result)
代码说明
- 预处理阶段:自动去掉每行首尾空格和末尾冗余逗号,过滤掉无价值的行,减少后续处理的干扰。
- 正则匹配:用
re.finditer一次性抓取每行中所有目标字段,不管是单独的Name行还是多字段商品行,都能统一生成对应子列表,完美适配你的需求。
变种:转换成字典格式(更适合Excel导入)
如果需要更贴合Excel表头的字典格式,可以修改处理逻辑:
import re # 原始文本同上,省略... # 1. 预处理过滤无效行(同上,省略...) # 2. 提取字典格式结果 dict_result = [] # 定义Excel表头对应的字段顺序 fields_order = ['Name', 'Price', 'Weight', 'Aisle', 'Shelf_life'] for line in valid_lines: item_dict = {} # 匹配每个字段的键值对 matches = re.findall(r'(Name|Price|Weight|Aisle|Shelf_life):\s*([^,]+)', line) for key, value in matches: item_dict[key] = value.strip() # 补全缺失字段(比如单独Name行的其他字段留空) for field in fields_order: if field not in item_dict: item_dict[field] = '' dict_result.append(item_dict) # 输出字典列表,可直接用pandas生成Excel表格 print(dict_result)
这种格式可以直接通过pandas.DataFrame(dict_result).to_excel('output.xlsx', index=False)快速写入Excel。
内容的提问来源于stack exchange,提问作者yawwml
相关产品推荐
相关产品推荐

