在txt文件中搜索和捕获字典值

问题描述 投票:0回答:1

我一直坚持从 txt 文件中提取特定数据。

我有一个txt文件,其中包含一些信息。

例如

公司名称 GmbH, Teststraße 24 , 01000 Sampleort 客户编号11111111 发票编号22222

发票地址 公司名称 2 mbH, Test2straße 11, 01001 Sample2ort 订单号。 555555 订购日期 01.01.1999

所以,我有类似上述信息的不同结构。有些文件包含发票编号,有些文件包含发票编号。编号:44444。我想把它们全部抓到。我想,我可以通过创建字典来捕获所有这些信息,例如:

`values_dict= {'Customer Number':'customer nr.', 'customer number', 
'cus. nr.', ... , 'Order Number':'order number', 'Order nr' ,....}`

并且,如何使用该字典从 txt 文件中捕获特定值?

我期待这样的输出:

订单号:555555 客户编号:11111111 发票号码:22222 订购日期:1999年1月1日

公司信息:公司名称 GmbH, Teststraße 24 , 01000 Sampleort 发票公司信息:公司名称 2 mbH, Test2straße 11, 01001 Sample2ort

python dictionary
1个回答
0
投票
Python 中的

re

 模块提供了对正则表达式的支持,允许您根据指定的模式搜索、匹配或拆分字符串。 
Python re 模块

import re # Your dictionary of keys with their possible variations values_dict = { 'Customer Number': ['Customer Nr.', 'customer number', 'cus. nr.', 'Customer Number'], 'Order Number': ['Order number.', 'Order nr', 'order number', 'Order Number'], 'Invoice Number': ['Invoice Nr.', 'Inv. Number:', 'invoice number', 'Invoice Number'], 'Order Date': ['Order Date'], 'Company Information': ['Company Name'], 'Invoice Company Information': ['Invoice Adress Company Name'] # Add more variations as needed } # Function to extract information based on the dictionary def extract_information(text, values_dict): results = {} for key, variations in values_dict.items(): for variation in variations: pattern = rf"{variation}[:]?[\s]*(.*)" match = re.search(pattern, text, re.IGNORECASE) if match: results[key] = match.group(1).strip() break return results text = """Company Name GmbH, Teststraße 24 , 01000 Sampleort Customer Nr. 11111111 Invoice Nr. 22222 Invoice Adress Company Name 2 mbH, Test2straße 11, 01001 Sample2ort Order number. 555555 Order Date 01.01.1999""" info = extract_information(text, values_dict) for key, value in info.items(): print(f"{key}: {value}")
    
© www.soinside.com 2019 - 2024. All rights reserved.