[英]converts an abnormal character into a normal character (e.g., an unicode character) in python
[英]Printing unicode character NAMES - e.g. 'GREEK SMALL LETTER ALPHA' - instead of 'α'
我正在測試函數isprintable()
。 我想打印字符串string.whitespace + unicodedata.lookup("GREEK SMALL LETTER ALPHA")
中所有字符的 Unicode NAMES 。
如何打印所有名稱 - 例如“SPACE”、“NO-BREAK SPACE”、“水平標簽”、“希臘小寫字母 ALPHA”。
import unicodedata, string
for e in string.whitespace + unicodedata.lookup("GREEK SMALL LETTER ALPHA"):
print(ord(e))
print(unicodedata.name(e))
我收到錯誤“ValueError:沒有這樣的名字”
32
SPACE
9
Traceback (most recent call last):
File "<stdin>", line 3, in <module>
ValueError: no such name
正如注釋所示,Unicode 數據庫沒有為每個字符命名,但NameAliases.txt
有。 下面解析該文件並返回一個別名(如果存在)。 在這種情況下,在文件中找到的第一個:
import string
import requests
import unicodedata as ud
# Pull the official NameAliases.txt from the matching Unicode database
# the current Python was built with.
response = requests.get(f'http://www.unicode.org/Public/{ud.unidata_version}/ucd/NameAliases.txt')
# Parse NameAliases.txt, storing the first instance of a code and a name
aliases = {}
for line in response.text.splitlines():
if not line.strip() or line.startswith('#'):
continue
code,name,_ = line.split(';')
val = chr(int(code,16))
if val not in aliases:
aliases[val] = name
# Return the first alias from NameAliases.txt if it exists when unicodedata.name() fails.
def name(c):
try:
return ud.name(c)
except ValueError:
return aliases.get(c,'<no name>')
for e in string.whitespace + ud.lookup("GREEK SMALL LETTER ALPHA"):
print(f'U+{ord(e):04X} {name(e)}')
輸出:
U+0020 SPACE
U+0009 CHARACTER TABULATION
U+000A LINE FEED
U+000D CARRIAGE RETURN
U+000B LINE TABULATION
U+000C FORM FEED
U+03B1 GREEK SMALL LETTER ALPHA
正如wjandrea在評論中鏈接的這個問答中提到的,ASCII 控制字符在當前的 Unicode 標准中沒有正式名稱,因此當您嘗試查找它們時會得到 ValueError。
標准庫中的curses.ascii
模塊為這些字符提供了兩個字符“名稱”的列表,對應於 ASCII 表中 Char 列中列出的名稱(由man ascii
顯示),但沒有描述。
所以我們可以這樣做
import string
import unicodedata
from curses.ascii import controlnames
for e in (string.whitespace + "\N{GREEK SMALL LETTER ALPHA}"):
try:
name = unicodedata.name(e)
except ValueError:
name = controlnames[ord(e)]
print(name)
給出這個結果
SPACE
HT
LF
CR
VT
FF
GREEK SMALL LETTER ALPHA
這並不理想,但可能是在不使用外部資源的情況下可以做到的最好的答案,就像在這個優秀的答案中所做的那樣。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.