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

如何将Mediastack API返回信息转为字典并修复法语字符乱码

实现方案

1. 乱码修复逻辑

你遇到的法语重音字符乱码是接口响应未正确使用UTF-8解码导致的,无需额外依赖,直接通过编码转义即可恢复:

  • 核心修复代码:fixed_text = broken_text.encode("latin-1").decode("utf-8")
  • 修复效果示例:原乱码pand�mie会被转为正确的pandémie,financi�res转为financières

2. Article对象转字典+批量修复乱码完整代码

def fix_french_encoding(content):
    # 仅处理字符串类型字段,非字符串直接返回
    if not isinstance(content, str):
        return content
    try:
        return content.encode("latin-1").decode("utf-8")
    except (UnicodeEncodeError, UnicodeDecodeError):
        # 转义失败直接返回原内容避免报错
        return content

def article_to_dict(article_obj):
    # 适配不同类型的Article对象转字典
    if hasattr(article_obj, "dict"):
        # 适配pydantic/dataclass等自带dict转换方法的对象
        article_dict = article_obj.dict()
    else:
        # 适配普通自定义类
        article_dict = article_obj.__dict__.copy()
    
    # 批量修复所有字符串字段的乱码
    for key, value in article_dict.items():
        article_dict[key] = fix_french_encoding(value)
    
    return article_dict

# 调用示例
article_dict = article_to_dict(你的Article对象)

额外优化建议

调用Mediastack接口时直接指定响应编码为UTF-8,可以从源头避免乱码产生,不需要后续转义:

import requests
resp = requests.get("你的Mediastack请求URL")
# 手动指定响应编码
resp.encoding = "utf-8"
# 直接解析为字典,无需后续转码
raw_article_data = resp.json()

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.28 03:36:05