
在日常数据处理中,我们经常会遇到需要从非结构化文本中提取关键信息,并将其与结构化数据(如json)进行关联匹配的场景。本教程将以一个具体示例,演示如何利用python的json模块进行json数据解析,re模块进行正则表达式匹配,从而实现从纯文本文件中识别设备名称,并在一个包含设备详细信息的json文件中找到对应的记录,最终提取出所需的url字段。
在开始编写代码之前,我们需要准备两个示例文件:一个JSON文件(test.json)和一个纯文本文件(test.txt)。
这个文件包含了多个设备的信息,每个设备都有一个唯一的名称和多个关联的URL。
{
"results": [
{
"url": "https://api.server.com/cables/100/",
"termination_a": {
"url": "https://api.server.com/interfaces/250/",
"device": {
"url": "https://api.server.com/devices/10/",
"display": "device-number1-2023-08 myname (1718)",
"name": "device-number1-2023-08 myname1"
}
}
},
{
"url": "https://api.server.com/cables/200/",
"termination_a": {
"url": "https://api.server.com/interfaces/160/",
"device": {
"url": "https://api.server.com/devices/22/",
"display": "device-number3-2023-08 myname (2245)",
"name": "device-number3-2023-08 myname3"
}
}
},
{
"url": "https://api.server.com/cables/300/",
"termination_a": {
"url": "https://api.server.com/interfaces/260/",
"device": {
"url": "https://api.server.com/devices/73/",
"display": "device-number8-2023-08 myname (3678)",
"name": "device-number8-2023-08 myname8"
}
}
}
]
}这个文件包含了一些描述性文本,其中嵌入了我们想要匹配的设备名称。
this is device-number1-2023-08 myname1 and it is good. this is device-number8-2023-08 myname8 and it is. this is device-number3-2023-08 myname3 and it is not good. this is an unmatched-device-name and it is irrelevant.
我们将通过以下步骤实现目标:
立即学习“Python免费学习笔记(深入)”;
import json
import re
def find_and_extract_urls(json_filepath, text_filepath):
"""
从文本文件中提取设备名称,并在JSON文件中查找匹配的设备,
然后打印出关联的URL信息。
Args:
json_filepath (str): JSON文件的路径。
text_filepath (str): 文本文件的路径。
"""
# 1. 读取并解析JSON文件
try:
with open(json_filepath, 'r', encoding='utf-8') as json_file:
json_data = json.load(json_file)
except FileNotFoundError:
print(f"错误: 未找到JSON文件 '{json_filepath}'")
return
except json.JSONDecodeError:
print(f"错误: JSON文件 '{json_filepath}' 格式不正确")
return
# 2. 读取文本文件内容
try:
with open(text_filepath, 'r', encoding='utf-8') as text_file:
text_content = text_file.read()
except FileNotFoundError:
print(f"错误: 未找到文本文件 '{text_filepath}'")
return
# 3. 使用正则表达式从文本内容中提取所有设备名称
# 正则表达式解释:
# (device-\w+-\d+-\d+ \w+): 捕获组,匹配 'device-' 开头,
# 接着是任意单词字符 (\w+),然后是两个数字组 (\d+),
# 最后是一个空格和任意单词字符 (\w+)。
# 示例匹配: "device-number1-2023-08 myname1"
txt_device_names = re.findall(r"(device-\w+-\d+-\d+ \w+)", text_content)
# 将提取到的名称转换为集合,以便O(1)时间复杂度进行查找,提高效率
txt_device_names_set = set(txt_device_names)
print(f"从文本文件 '{text_filepath}' 中提取到的设备名称: {txt_device_names_set}\n")
# 4. 遍历JSON数据,查找匹配项并提取URL
found_matches = False
for item in json_data.get("results", []): # 使用.get()处理'results'键可能不存在的情况
device_info = item.get("termination_a", {}).get("device", {})
json_device_name = device_info.get("name")
if json_device_name and json_device_name in txt_device_names_set:
found_matches = True
print(f"匹配成功!设备名称 --> {json_device_name}")
print(f" 根URL: {item.get('url', 'N/A')}")
print(f" termination_a URL: {item.get('termination_a', {}).get('url', 'N/A')}")
# 如果需要,还可以打印其他URL,例如 termination_a device URL
# print(f" termination_a device URL: {device_info.get('url', 'N/A')}")
print("-" * 30)
if not found_matches:
print("未找到任何匹配的设备名称。")
# 调用函数执行匹配和提取
if __name__ == "__main__":
json_file_path = 'test.json'
text_file_path = 'test.txt'
find_and_extract_urls(json_file_path, text_file_path)
执行上述Python脚本,你将看到如下输出:
从文本文件 'test.txt' 中提取到的设备名称: {'device-number8-2023-08 myname8', 'device-number1-2023-08 myname1', 'device-number3-2023-08 myname3'}
匹配成功!设备名称 --> device-number1-2023-08 myname1
根URL: https://api.server.com/cables/100/
termination_a URL: https://api.server.com/interfaces/250/
------------------------------
匹配成功!设备名称 --> device-number3-2023-08 myname3
根URL: https://api.server.com/cables/200/
termination_a URL: https://api.server.com/interfaces/160/
------------------------------
匹配成功!设备名称 --> device-number8-2023-08 myname8
根URL: https://api.server.com/cables/300/
termination_a URL: https://api.server.com/interfaces/260/
------------------------------本教程展示了如何结合Python的文件I/O、JSON解析和正则表达式,高效地从非结构化文本中提取信息,并与结构化数据进行匹配和关联。这种方法在数据清洗、数据集成和自动化报告等多种场景下都非常实用。通过理解并灵活运用这些技术,你可以构建出强大的数据处理脚本,以
以上就是Python中基于文本匹配JSON数据并提取关联URL信息的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号