You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何调整Python正则提取水果数据的输出对齐格式?

Python正则提取水果数量的输出格式修正方案

核心思路

问题根源是你之前的代码把数字和水果名称分开提取,没有建立对应绑定关系。解决的关键是一次性匹配水果名称和对应数量,生成键值对,再处理剩余未关联的数字。

修改后的代码示例

import re

# 替换成你的实际发票文本
invoice_text = """
Watermeloenen: 466
Appels: 1200
Peren: 890
Totaal: 2556
Bestelnummer: 789
"""

# 1. 匹配水果名称和对应数量,生成字典
fruit_match_pattern = re.compile(r'([\w-]+):\s*(\d+)')
fruit_count_dict = dict(fruit_match_pattern.findall(invoice_text))

# 2. 提取所有数字,过滤掉已和水果绑定的数字
all_extracted_numbers = re.findall(r'\d+', invoice_text)
used_numbers = set(fruit_count_dict.values())
remaining_numbers = [num for num in all_extracted_numbers if num not in used_numbers]

# 3. 按要求格式输出
print("水果统计:")
for fruit_name, count in fruit_count_dict.items():
    print(f"{fruit_name}: {count}")

print("\n剩余未匹配数字:")
for num in remaining_numbers:
    print(num)

关键说明

  • 正则([\w-]+):\s*(\d+):[\w-]+适配带连字符的水果名,\s*匹配名称和数字之间的任意空白,避免漏匹配。
  • 用字典存储水果和数量,保证输出时一一对应,自然对齐。
  • 过滤已使用的数字,避免重复输出,剩余数字单独换行打印。

内容的提问来源于stack exchange,提问作者mightycode Newton

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.12 14:41:31