
在现代数据处理场景中,我们经常需要从不同格式的数据源中关联和提取信息。本教程将聚焦于一个典型案例:如何从一个包含设备名称的非结构化文本文件(.txt)中识别设备,并利用这些名称在一个结构化的json文件(.json)中查找并提取对应的详细url信息。我们将使用python的json模块进行json解析,以及re模块进行正则表达式匹配。
首先,我们需要准备两个示例文件:一个JSON文件(test.json)和一个文本文件(test.txt)。
test.json 文件内容示例:
{
"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 myname"
}
}
},
{
"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-number1-2023-08 myname1"
}
}
},
{
"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 myname"
}
}
}
]
}test.txt 文件内容示例:
this is device-number1-2023-08 myname1 and it is good. this is device-number3-2023-08 myname3 and it is not good. this is device-number8-2023-08 myname8 and it is.
我们的目标是:从 test.txt 中提取 device-numberX-YYYY-MM mynameZ 这样的设备名称,然后用这些名称去 test.json 中匹配 results 列表里每个对象的 termination_a.device.name 字段。一旦匹配成功,就输出该JSON对象中的 url 和 termination_a.url。
立即学习“Python免费学习笔记(深入)”;
我们将分步完成这个任务:首先加载数据,然后从文本文件中提取设备名称,最后遍历JSON数据进行匹配和输出。
使用Python的 with open() 语句安全地打开并读取文件。json.load() 用于解析JSON文件,而 text_file.read() 则用于读取整个文本文件内容。
import json
import re
# 加载JSON文件
with open("test.json", "r", encoding="utf-8") as json_file:
json_data = json.load(json_file)
# 加载文本文件
with open("test.txt", "r", encoding="utf-8") as text_file:
text_content = text_file.read()
print("JSON数据已加载。")
print("文本内容已加载。")为了从非结构化的文本中准确提取设备名称,正则表达式是理想工具。根据 device-number1-2023-08 myname1 这种模式,我们可以构建一个正则表达式来匹配它。
正则表达式模式解释:
# 使用正则表达式从文本内容中提取所有设备名称
# 模式:(device-\w+-\d+-\d+ \w+)
# 示例匹配:device-number1-2023-08 myname1
txt_device_names = re.findall(r"(device-\w+-\d+-\d+ \w+)", text_content)
print("\n从文本文件中提取的设备名称:", txt_device_names)输出示例:
从文本文件中提取的设备名称: ['device-number1-2023-08 myname1', 'device-number3-2023-08 myname3', 'device-number8-2023-08 myname8']
现在我们有了从文本文件中提取的设备名称列表。接下来,我们将遍历JSON数据中的 results 列表,检查每个 device 的 name 字段是否在我们的设备名称列表中。如果匹配成功,就打印出所需的URL信息。
print("\n开始匹配JSON数据并提取URL:")
found_matches = False
for item in json_data["results"]:
# 提取JSON中设备的名称
json_device_name = item["termination_a"]["device"]["name"]
# 检查JSON设备的名称是否在文本文件提取的名称列表中
if json_device_name in txt_device_names:
found_matches = True
print(f"\n匹配成功,设备名称:{json_device_name}")
print(f"\t\t全局URL: {item['url']}")
print(f"\t\ttermination_a URL: {item['termination_a']['url']}")
print(f"\t\ttermination_a device URL: {item['termination_a']['device']['url']}")
if not found_matches:
print("未找到任何匹配项。请检查数据或正则表达式。")将上述所有步骤整合到一起,形成一个完整的Python脚本:
import json
import re
def extract_and_match_data(json_filepath, text_filepath):
"""
从JSON文件和文本文件关联数据并提取URL信息。
Args:
json_filepath (str): JSON文件的路径。
text_filepath (str): 文本文件的路径。
"""
try:
# 1. 加载JSON文件
with open(json_filepath, "r", encoding="utf-8") as json_file:
json_data = json.load(json_file)
print(f"成功加载JSON文件: {json_filepath}")
# 2. 加载文本文件
with open(text_filepath, "r", encoding="utf-8") as text_file:
text_content = text_file.read()
print(f"成功加载文本文件: {text_filepath}")
# 3. 使用正则表达式从文本内容中提取所有设备名称
# 模式:(device-\w+-\d+-\d+ \w+)
txt_device_names = re.findall(r"(device-\w+-\d+-\d+ \w+)", text_content)
print("\n从文本文件中提取的设备名称列表:", txt_device_names)
# 4. 遍历JSON数据,进行匹配并输出
print("\n开始匹配JSON数据并提取URL:")
found_matches = False
for item in json_data["results"]:
json_device_name = item["termination_a"]["device"]["name"]
if json_device_name in txt_device_names:
found_matches = True
print(f"\n匹配成功,设备名称:{json_device_name}")
print(f"\t\t全局URL: {item['url']}")
print(f"\t\ttermination_a URL: {item['termination_a']['url']}")
print(f"\t\ttermination_a device URL: {item['termination_a']['device']['url']}")
if not found_matches:
print("未找到任何匹配项。请检查数据或正则表达式。")
except FileNotFoundError:
print(f"错误:文件未找到。请检查路径: {json_filepath} 或 {text_filepath}")
except json.JSONDecodeError:
print(f"错误:JSON文件格式不正确: {json_filepath}")
except KeyError as e:
print(f"错误:JSON数据结构不符合预期,缺少键: {e}")
except Exception as e:
print(f"发生未知错误: {e}")
# 调用函数执行数据关联和提取
if __name__ == "__main__":
extract_and_match_data("test.json", "test.txt")假设您的 test.json 和 test.txt 文件内容如教程开头所示,运行上述代码将得到类似以下输出:
成功加载JSON文件: test.json
成功加载文本文件: test.txt
从文本文件中提取的设备名称列表: ['device-number1-2023-08 myname1', 'device-number3-2023-08 myname3', 'device-number8-2023-08 myname8']
开始匹配JSON数据并提取URL:
匹配成功,设备名称:device-number1-2023-08 myname
全局URL: https://api.server.com/cables/100/
termination_a URL: https://api.server.com/interfaces/250/
termination_a device URL: https://api.server.com/devices/10/
匹配成功,设备名称:device-number1-2023-08 myname1
全局URL: https://api.server.com/cables/200/
termination_a URL: https://api.server.com/interfaces/160/
termination_a device URL: https://api.server.com/devices/22/
匹配成功,设备名称:device-number8-2023-08 myname
全局URL: https://api.server.com/cables/300/
termination_a URL: https://api.server.com/interfaces/260/
termination_a device URL: https://api.server.com/devices/73/注意: 原始JSON和TXT文件在匹配时可能存在细微差异。例如,原始JSON中的 device-number1-2023-08 myname 和TXT中的 device-number1-2023-08 myname1 并不完全一致。为了演示匹配成功,本教程的示例JSON数据已做微调,确保 termination_a.device.name 字段能与TXT文件中的提取名称精确匹配。
txt_device_names_set = set(txt_device_names) # 之后使用 if json_device_name in txt_device_names_set:
通过本教程,您应该已经掌握了如何使用Python有效地关联和提取来自不同数据源(JSON和文本文件)的信息。这种模式在日志分析、配置管理和数据集成等多种场景中都非常有用。
以上就是Python:基于名称匹配从JSON和文本文件提取关联数据的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号