在 Python 中將 Unicode 字元轉換為 ASCII 字串

Rayven Esplanada 2021年7月18日
在 Python 中將 Unicode 字元轉換為 ASCII 字串

Unicode 字元是所有語言字元的全域性編碼標準。與僅支援每個字元一個位元組的 ASCII 不同,Unicode 字元將此功能擴充套件到 4 個位元組,從而使其支援任何語言的更多字元。

本教程演示瞭如何將 Unicode 字元轉換為 ASCII 字串。目標是刪除 ASCII 不支援的字元,或將 Unicode 字元替換為其相應的 ASCII 字元。

在 Python 中使用 unicodedata.normalize()encode() 將 Unicode 轉換為 ASCII 字串

Python 模組 unicodedata 提供了一種利用 Unicode 和實用程式功能中的字元資料庫的方法,這些功能大大簡化了對這些字元的訪問、過濾和查詢。

unicodedata 具有一個名為 normalize()的函式,該函式接受兩個引數,即 Unicode 字串的規範化形式和給定的字串。

規範化的 Unicode 格式有 4 種型別:NFCNFKCNFDNFKD。要了解更多資訊,可以使用官方文件來詳細瞭解每種型別。本教程將全程使用 NFKD 規範化形式。

讓我們宣告一個包含多個 unicode 字元的字串。

import unicodedata

stringVal = u"Här är ett exempel på en svensk mening att ge dig."

print(unicodedata.normalize("NFKD", stringVal).encode("ascii", "ignore"))

呼叫 normalize() 方法後,將呼叫連結到函式 encode(),該函式將完成從 Unicode 到 ASCII 的轉換。

字串值之前的 u 字元可幫助 Python 識別字串值包含 unicode 字元;這樣做是出於型別安全的目的。

第一個引數指定轉換型別,第二個引數強制執行字元無法轉換時應執行的操作。在這種情況下,第二個引數傳遞 ignore,它將忽略任何無法轉換的字元。

輸出:

b'Har ar ett exempel pa en svensk mening att ge dig.'

請注意,原始字串(äå)中的 unicode 字元已被其 ASCII 字元對等體(a)取代。

字串開頭的 b 符號表示該字串是位元組文字,因為在字串上使用了 encode() 函式。要刪除符號和封裝字串的單引號,請在呼叫 encode() 之後將其鏈式呼叫 decode(),以將其重新轉換為字串文字。

print(unicodedata.normalize("NFKD", stringVal).encode("ascii", "ignore").decode())

輸出:

Har ar ett exempel pa en svensk mening att ge dig.

讓我們嘗試另一個示例,該示例使用 replace 作為 encode() 函式中的第二個引數。

對於此示例,讓我們嘗試一個字串,該字串具有不包含 ASCII 對應字元的字元。

import unicodedata

stringVal = u"áæãåāœčćęßßßわた"

print(unicodedata.normalize("NFKD", stringVal).encode("ascii", "replace").decode())

此示例字串中的所有字元均未以 ASCII 進行註冊,但可能具有對應的符號。

輸出:

a??a?a?a??c?c?e??????

replace 引數直接將沒有 ASCII 對應的字元替換成問號 ? 符號。如果我們在同一字串上使用 ignore

print(unicodedata.normalize("NFKD", stringVal).encode("ascii", "ignore").decode())

輸出將是:

aaaacce

總之,要將 Unicode 字元轉換為 ASCII 字元,請使用 unicodedata 模組中的 normalize() 函式和字串的內建 encode() 函式。你可以忽略或替換沒有 ASCII 對應字元的 Unicode 字元。ignore 選項將刪除該字元,而 replace 選項將其替換為問號。

Rayven Esplanada avatar Rayven Esplanada avatar

Skilled in Python, Java, Spring Boot, AngularJS, and Agile Methodologies. Strong engineering professional with a passion for development and always seeking opportunities for personal and career growth. A Technical Writer writing about comprehensive how-to articles, environment set-ups, and technical walkthroughs. Specializes in writing Python, Java, Spring, and SQL articles.

LinkedIn

相關文章 - Python String