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

Python中解码双向字节(iso-8859-8-i/iso-8859-8-e)的方法求助

解决Python解码iso-8859-8-i/iso-8859-8-e邮件头的问题

Python标准库并未直接支持RFC1556定义的iso-8859-8-i和iso-8859-8-e编码,这两个是iso-8859-8的双向文本变体:

  • iso-8859-8-i:逻辑顺序(按阅读顺序存储字符)
  • iso-8859-8-e:视觉顺序(按屏幕显示顺序存储字符)

核心解决思路分两步:

1. 完成字符解码

这两个变体的字符集和iso-8859-8完全一致,仅文本排列方向不同,因此可先替换编码名称为标准的iso-8859-8再解码:

def decode_iso_8859_8_variant(encoded_bytes, encoding):
    # 替换为标准编码名称
    standard_encoding = encoding.replace("-i", "").replace("-e", "")
    # 解码字节内容
    decoded_text = encoded_bytes.decode(standard_encoding)
    return decoded_text

2. 处理双向文本顺序

解码后若需调整文本显示/存储顺序,可借助第三方库python-bidi处理Unicode双向算法:

  • 先安装库:pip install python-bidi
  • 示例代码:
from bidi.algorithm import get_display

# iso-8859-8-i(逻辑顺序)转视觉显示顺序
logical_text = decode_iso_8859_8_variant(your_encoded_bytes, "iso-8859-8-i")
visual_text = get_display(logical_text)

# iso-8859-8-e(视觉顺序)转逻辑存储顺序
visual_text_e = decode_iso_8859_8_variant(your_encoded_bytes_e, "iso-8859-8-e")
logical_text_e = get_display(visual_text_e, is_rtl=True)

针对MIME编码邮件头的额外处理

如果邮件头是MIME编码格式(如=?iso-8859-8-i?B?...?=),可结合Python标准库email.header模块,配合编码替换逻辑处理:

from email.header import decode_header

def decode_mime_header(header_str):
    decoded_parts = []
    for part, encoding in decode_header(header_str):
        if encoding:
            # 标准化编码名称
            standardized_enc = encoding.lower().replace("-i", "").replace("-e", "")
            decoded_part = part.decode(standardized_enc)
            # 根据原编码处理双向顺序
            if encoding.endswith("-i"):
                decoded_part = get_display(decoded_part)
            elif encoding.endswith("-e"):
                decoded_part = get_display(decoded_part, is_rtl=True)
            decoded_parts.append(decoded_part)
        else:
            decoded_parts.append(str(part))
    return "".join(decoded_parts)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.03 19:28:09