如何将Hugging Face Pipeline的结果存储为合法JSON?
解决方法
原代码的核心问题
- 每次处理文件时未清空
sents列表,导致不同文件的结果相互污染 - 循环内重复初始化pipeline,严重拖慢效率
- 直接使用Python字典结构而非JSON序列化工具,导致生成的内容不符合JSON规范(比如单引号、Python特有的数据格式)
修正后的代码
import os import json import xml.etree.ElementTree as ET from transformers import AutoTokenizer, AutoModelForTokenClassification, pipeline words_input_dir = "MYDIRECTORY OF TXT FILES" os.chdir(words_input_dir) # 只初始化一次pipeline,提升效率 label_list = ['literal', "metaphoric"] label_dict_relations = {i: l for i, l in enumerate(label_list)} tokenizer = AutoTokenizer.from_pretrained("lwachowiak/Metaphor-Detection-XLMR") model = AutoModelForTokenClassification.from_pretrained( "lwachowiak/Metaphor-Detection-XLMR", id2label=label_dict_relations ) nerpipeline = pipeline('ner', model=model, tokenizer=tokenizer, aggregation_strategy="simple") resu = {} for filename in os.listdir(words_input_dir): if filename.endswith(".xml"): sents = [] # 每个文件单独初始化列表,避免结果累加 tree = ET.parse(filename) root = tree.getroot() node = root.findall("./body/sec/p") for x in node: if x is not None and x.text: # 过滤空文本,避免无效处理 coco = x.text.strip() data = nerpipeline(coco) sents.append(data) resu[filename] = {"sentence": sents} # 生成合法JSON并保存到文件 with open("metaphor_detection_results.json", "w", encoding="utf-8") as f: json.dump(resu, f, ensure_ascii=False, indent=2)
关键修正点说明
- pipeline初始化优化:把pipeline创建移到文件循环外,避免重复加载模型和tokenizer,大幅提升处理速度
- 列表独立初始化:每个XML文件处理前重新创建
sents列表,确保不同文件的结果互不干扰 - 标准JSON序列化:使用
json.dump()将Python字典转换为合规JSON格式,自动处理单引号转双引号、数据类型兼容等问题,生成的文件可直接用于后续操作 - 空内容过滤:增加
x.text非空判断,避免处理无意义的空文本
额外说明
如果不需要保存到文件,而是直接获取JSON字符串,可使用json.dumps(resu, ensure_ascii=False, indent=2),返回的就是可直接使用的合法JSON字符串。
内容的提问来源于stack exchange,提问作者Idkwhatywantmed
相关产品推荐
相关产品推荐

