簡體   English   中英

如何將帶有斯堪的納維亞字符的UTF字符串轉換為ASCII?

[英]How to convert an UTF string with scandinavian characters to ASCII?

我想轉換這個字符串

foo_utf = u'nästy chäräctörs with å and co.' # unicode

進入這個

foo_ascii = 'nästy chäräctörs with å and co.' # ASCII

知道如何在Python(2.6)中執行此操作嗎? 我找到了unicodedata模塊,但不知道如何進行轉換。

我認為你不能。 那些“討厭的字符”無法編碼為ASCII,因此您必須選擇其他編碼(UTF-8或Latin-1或Windows-1252或其他某種編碼)。

嘗試字符串的encode方法。

>>> u'nästy chäräctörs with å and co.'.encode('latin-1')
'n\xe4sty ch\xe4r\xe4ct\xf6rs with \xe5 and co.'

python stdlib中的codecs模塊中有多個選項,具體取決於您希望擴展字符的處理方式:

>>> import codecs
>>> u = u'nästy chäräctörs with å and co.'
>>> encode = codecs.get_encoder('ascii')
>>> encode(u) 
'
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
UnicodeEncodeError: 'ascii' codec can't encode character u'\xe4' in position 1: ordinal not in range(128)
>>> encode(u, 'ignore')
('nsty chrctrs with  and co.', 31)
>>> encode(u, 'replace')
('n?sty ch?r?ct?rs with ? and co.', 31)
>>> encode(u, 'xmlcharrefreplace')
('n&#228;sty ch&#228;r&#228;ct&#246;rs with &#229; and co.', 31)
>>> encode(u, 'backslashreplace')
('n\\xe4sty ch\\xe4r\\xe4ct\\xf6rs with \\xe5 and co.', 31)

希望其中之一可以滿足您的需求。 Python編解碼器模塊文檔中提供了更多信息。

您還可以使用python中提供的unicodedata模塊( http://docs.python.org/library/unicodedata.html )將許多unicode值轉換為Ascii變體。 IE修復了不同的“ s”之類的問題。緊接着使用encode()方法,您可以完全清除字符串。

您主要對unicodedata中的內容進行規范化並將其傳遞給NFKC標志的方法。

這確實是一個Django問題,而不是python問題。 如果該字符串位於您的.py文件之一中,請確保文件頂部有以下行: -*- coding: utf-8 -*-

此外,您的字符串必須為“ unicode”類型(u'foobar')

然后確保您的html頁面可以使用unicode:

<meta http-equiv="content-type" content="text/html;charset=utf-8" />

這應該可以解決所有問題。 無需編碼/解碼等。只需確保所有內容都是unicode,並且您就安全起見。

暫無
暫無

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

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