簡體   English   中英

在Python中將html實體轉換為ascii

[英]Convert html entities to ascii in Python

我需要使用Python將任何html實體轉換為其ASCII等價物。 我的用例是我正在清理一些用於構建電子郵件的HTML,以便從HTML創建明文電子郵件。

現在,當我需要ASCII(我認為)時,我才真正知道如何從這些實體創建unicode,以便明文電子郵件能夠正確讀取帶有重音字符的內容。 我認為一個基本的例子是html實體“á” 或者á被編碼為ASCII。

此外,我甚至不能確定ASCII是明文電子郵件所需要的。 你可以告訴我,我完全迷失在這個編碼的東西上。

這是一個完整的實現,也可以處理unicode html實體。 你可能會發現它很有用。

它返回一個不是ascii的unicode字符串,但是如果你想要簡單的ascii,你可以修改替換操作,以便它將實體替換為空字符串。

def convert_html_entities(s):
    matches = re.findall("&#\d+;", s)
    if len(matches) > 0:
        hits = set(matches)
        for hit in hits:
            name = hit[2:-1]
            try:
                entnum = int(name)
                s = s.replace(hit, unichr(entnum))
            except ValueError:
                pass

    matches = re.findall("&#[xX][0-9a-fA-F]+;", s)
    if len(matches) > 0:
        hits = set(matches)
        for hit in hits:
            hex = hit[3:-1]
            try:
                entnum = int(hex, 16)
                s = s.replace(hit, unichr(entnum))
            except ValueError:
                pass

    matches = re.findall("&\w+;", s)
    hits = set(matches)
    amp = "&"
    if amp in hits:
        hits.remove(amp)
    for hit in hits:
        name = hit[1:-1]
        if htmlentitydefs.name2codepoint.has_key(name):
            s = s.replace(hit, unichr(htmlentitydefs.name2codepoint[name]))
    s = s.replace(amp, "&")
    return s 

編輯:添加十六進制匹配。 我已經使用了一段時間了,並且遇到了'這是單引號/撇號的第一種情況。

ASCII是美國信息交換標准代碼, 包含任何帶重音的字母。 你最好的選擇是獲得Unicode(正如你所說的那樣)並將其編碼為UTF-8(如果您正在處理嚴重錯誤編碼的用戶代理/客戶,嘆息時可能是ISO-8859-1或一些奇怪的代碼頁) - - 該部分的內容類型標題以及text / plain可以表示您選擇使用的編碼(我建議嘗試使用UTF-8,除非您已經證明它無法正常工作 - 這幾天幾乎得到普遍支持而且還有更多比任何ISO-8859或“代碼頁”黑客都靈活!)。

您可以使用htmlentitydefs包:

import htmlentitydefs
print htmlentitydefs.entitydefs['aacute']

基本上, entitydefs只是一個字典,您可以通過在python提示符下打印來看到它:

from pprint import pprint 
pprint htmlentitydefs.entitydefs

我們用agazso的功能建立了一個小模塊:

http://github.com/ARTFL/util/blob/master/ents.py

我們發現agazso的功能比ent轉換的替代方案更快。 謝謝你發布它。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM