簡體   English   中英

將 html 實體文件轉換為 Unicode(使用 BeautifulSoup 和 Python?)

[英]Convert html entities file to Unicode (with BeautifulSoup and Python?)

我已經在 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 做小部分(使用 Edit > Encode/Decode Selection -> HTML/XML character reference to 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)

BeautifulSoup 有一個內置函數來執行此操作,稱為.decode() 當您讀入文件時,只需將其添加到行尾即可!

例子:

site_read = site_download.read().decode('utf-8')
import bs4

html = '''<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>'''

soup = bs4.BeautifulSoup(html, 'lxml')

出去:

<html><body><b>γέρων</b>, <i>οντος, ὁ</i>, Wurzel <i>ΓΕΡ</i>, verwandt mit <i>γέρας, γεραρός, γεραιός</i></body></html>

文件

要解析文檔,請將其傳遞給 BeautifulSoup 構造函數。 您可以傳入一個字符串或一個打開的文件句柄:

from bs4 import BeautifulSoup
> 
> soup = BeautifulSoup(open("index.html"))  # you can open you file in here
> 
> soup = BeautifulSoup("<html>data</html>")

首先,將文檔轉換為 Unicode然后將 HTML 實體轉換為 Unicode 字符:

感謝您的幫助,我確實使用最新版本的 EmEditor 很容易地做到了,事實證明它非常快:

選擇文本 > 編輯 > 編碼/解碼選擇 - > HTML/XML 對 Unicode 的字符引用

暫無
暫無

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

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