Skip to main content
 首页 » 编程设计

python之将 html 实体文件转换为 Unicode(使用 BeautifulSoup 和 Python)

2024年10月17日8落叶

我在Win10上安装了Python 2.7.13、pip和beautifulsoup。我想将一个带有 html 实体的大文件转换为 Unicode 字符,但我不确定该怎么做(我对 Python 了解不多)。文件内容如下所示:

<b>&#947;&#941;&#961;&#969;&#957;</b>, <i>&#959;&#957;&#964;&#959;&#962;, &#8001;</i>, Wurzel <i>&#915;&#917;&#929;</i>, verwandt mit <i>&#947;&#941;&#961;&#945;&#962;, &#947;&#949;&#961;&#945;&#961;&#972;&#962;, &#947;&#949;&#961;&#945;&#953;&#972;&#962;</i> 

我可以用 EmEditor 做小部分(使用编辑 > 编码/解码选择 -> HTML/XML 字符引用到 Unicode)但是它太慢而且无法处理大文件转换。

我很乐意为此提供任何(离线)解决方案。

请您参考如下方法:

这是 html 编码的,试试这个:

from HTMLParser import HTMLParser 
 
f = open("myfile.txt") 
h = HTMLParser() 
new_file_content = h.unescape(f.read()) 
new_file = open("newfile.txt", 'w') 
new_file.write(new_file_content)