導航:首頁 > 編程語言 > python27全形轉半形

python27全形轉半形

發布時間:2023-03-09 16:56:10

python怎麼判斷中文字元編碼

#!/usr/bin/env python
# -*- coding:GBK -*-

"""漢字處理的工具:
判斷unicode是否是漢字,數字,英文,或者其他字元。
全形符號轉半形符號。"""

__author__="internetsweeper <[email protected]>"
__date__="2007-08-04"

def is_chinese(uchar):
"""判斷一個unicode是否是漢字"""
if uchar >= u'\u4e00' and uchar<=u'\u9fa5':
return True
else:
return False

def is_number(uchar):
"""判斷一個unicode是否是數字"""
if uchar >= u'\u0030' and uchar<=u'\u0039':
return True
else:
return False

def is_alphabet(uchar):
"""判斷一個unicode是否是英文字母"""
if (uchar >= u'\u0041' and uchar<=u'\u005a') or (uchar >= u'\u0061' and uchar<=u'\u007a'):
return True
else:
return False

def is_other(uchar):
"""判斷是否非漢字,數字和英文字元"""
if not (is_chinese(uchar) or is_number(uchar) or is_alphabet(uchar)):
return True
else:
return False

def B2Q(uchar):
"""半形轉全形"""
inside_code=ord(uchar)
if inside_code<0x0020 or inside_code>0x7e: #不是半形字元就返回原來的字元
return uchar
if inside_code==0x0020: #除了空格其他的全形半形的公式為:半形=全形-0xfee0
inside_code=0x3000
else:
inside_code+=0xfee0
return unichr(inside_code)

def Q2B(uchar):
"""全形轉半形"""
inside_code=ord(uchar)
if inside_code==0x3000:
inside_code=0x0020
else:
inside_code-=0xfee0
if inside_code<0x0020 or inside_code>0x7e: #轉完之後不是半形字元返回原來的字元
return uchar
return unichr(inside_code)

def stringQ2B(ustring):
"""把字元串全形轉半形"""
return "".join([Q2B(uchar) for uchar in ustring])

def uniform(ustring):
"""格式化字元串,完成全形轉半形,大寫轉小寫的工作"""
return stringQ2B(ustring).lower()

def string2List(ustring):
"""將ustring按照中文,字母,數字分開"""
retList=[]
utmp=[]
for uchar in ustring:
if is_other(uchar):
if len(utmp)==0:
continue
else:
retList.append("".join(utmp))
utmp=[]
else:
utmp.append(uchar)
if len(utmp)!=0:
retList.append("".join(utmp))
return retList

if __name__=="__main__":
#test Q2B and B2Q
for i in range(0x0020,0x007F):
print Q2B(B2Q(unichr(i))),B2Q(unichr(i))

#test uniform
ustring=u'中國 人名a高頻A'
ustring=uniform(ustring)
ret=string2List(ustring)
print ret

以上轉自http://hi..com/fenghua1893/item/d1a71d5ac47ffdcfd3e10cd1

這個問題是做 MkIV 預處理程序時搞定的,就是把一個混合了中英文混合字串分離為英文與中文的子字串,譬如,將 」我的 English 學的不好「 分離為 「我的"、" English 」 與 "學的不好" 三個子字串。
1. 中英文混合字串的統一編碼表示中英文混合字串處理最省力的辦法就是把它們的編碼都轉成 Unicode,讓一個漢字與一個英文字母的內存位寬都是相等的。這個工作用 Python 來做,比較合適,因為 Python 內碼採用的是 Unicode,並且為了支持 Unicode 字串的操作,Python 做了一個 Unicode 內建模塊,把 string 對象的全部方法重新實現了一遍,另外提供了 Codecs 對象,解決各種編碼類型的字元串解碼與編碼問題。
譬如下面的 Python 代碼,可實現 UTF-8 編碼的中英文混合字串向 Unicode 編碼的轉換:# -*-
coding:utf-8 -*-
a = "我的 English 學的不好"
print type(a),len (a), a
b = unicode (a, "utf-8")
print type(b), len (b), b字元串 a 是 utf-8 編碼,使用 python 的內建對象 unicode 可將其轉換為 Unicode 編碼的字元串 b。上述代碼執行後的輸出結果如下所示,比較字串 a 與字串 b 的長度,顯然 len (b) 的輸出結果是合理的。<type 'str'> 27 我的 English 學的不好
<type 'unicode'> 15 我的 English 學的不好要注意的一個問題是 Unicode 雖然號稱是「統一碼」,不過也是存在著兩種形式,即:
UCS-2:為 16 位碼,具有 2^16 = 65536 個碼位; UCS-4:為 32 位碼,目前的規定是其首位元組的首位為 0,因此具有 2^31 = 2147483648 個碼位,不過現在的只使用了 0x00000000 - 0x0010FFFF 之間的碼位,共 1114112 個。
使用Python sys 模塊提供的一個變數 maxunicode 的值可以判斷當前 Python 所使用的 Unicode 類型是 UCS-2 的還是 UCS-4 的。import sys
print sys.maxunicode若 sys.maxunicode 的值為 1114111,即為 UCS-4;若為 65535,則為 UCS-2。

2. 中英文混合字串的分離一旦中英文字串的編碼獲得統一,那麼對它們進行分裂就是很簡單的事情了。首先要為中文字串與英文字串分別准備一個收集器,使用兩個空的字串對象即可,譬如 zh_gather 與 en_gather;然後要准備一個列表對象,負責按分離次序存儲 zh_gather 與 en_gather 的值。下面這個 Python 函數接受一個中英文混合的 Unicode 字串,並返回存儲中英文子字串的列表。def split_zh_en (zh_en_str):

zh_en_group = []
zh_gather = ""
en_gather = ""
zh_status = False

for c in zh_en_str:
if not zh_status and is_zh (c):
zh_status = True
if en_gather != "":
zh_en_group.append ([mark["en"],en_gather])
en_gather = ""
elif not is_zh (c) and zh_status:
zh_status = False
if zh_gather != "":
zh_en_group.append ([mark["zh"], zh_gather])
if zh_status:
zh_gather += c
else:
en_gather += c
zh_gather = ""

if en_gather != "":
zh_en_group.append ([mark["en"],en_gather])
elif zh_gather != "":
zh_en_group.append ([mark["zh"],zh_gather])

return zh_en_group上述代碼所實現的功能細節是:對中英文混合字串 zh_en_str 的遍歷過程中進行逐字識別,若當前字元為中文,則將其添加到 zh_gather 中;若當前字元為英文,則將其添加到 en_gather 中。zh_status 表示中英文字元的切換狀態,當 zh_status 的值發生突變時,就將所收集的中文子字串或英文子字串添加到 zh_en_group 中去。
判斷字串 zh_en_str 中是否包含中文字元的條件語句中出現了一個 is_zh () 函數,它的實現如下:def is_zh (c):
x = ord (c)
# Punct & Radicals
if x >= 0x2e80 and x <= 0x33ff:
return True

# Fullwidth Latin Characters
elif x >= 0xff00 and x <= 0xffef:
return True

# CJK Unified Ideographs &
# CJK Unified Ideographs Extension A
elif x >= 0x4e00 and x <= 0x9fbb:
return True
# CJK Compatibility Ideographs
elif x >= 0xf900 and x <= 0xfad9:
return True

# CJK Unified Ideographs Extension B
elif x >= 0x20000 and x <= 0x2a6d6:
return True

# CJK Compatibility Supplement
elif x >= 0x2f800 and x <= 0x2fa1d:
return True

else:
return False這段代碼來自 jjgod 寫的 XeTeX 預處理程序。
對於分離出來的中文子字串與英文子字串,為了使用方便,在將它們存入 zh_en_group 列表時,我對它們分別做了標記,即 mark["zh"] 與 mark["en"]。mark 是一個 dict 對象,其定義如下:mark = {"en":1, "zh":2}如果要對 zh_en_group 中的英文字串或中文字串進行處理時,標記的意義在於快速判定字串是中文的,還是英文的,譬如:for str in zh_en_group:
if str[0] = mark["en"]:
do somthing
else:
do somthing

Ⅱ 如何理解python3的unicode,以及全形半形轉換

1. unicode是一個編碼的standard,表明了字元與數字之間的映射,是可變長的。

2. 映射後的數據如何編碼為位元組?這個就是具體的編碼規則:目前最主流的是UTF-8,同樣,它也是變字長的。

python3中的str都是unicode的:「The default encoding for Python source code is UTF-8」

python3中的encode:按照encode()括弧中的參數對字元串進行編碼,就是生成bytes。

所以:

In:'中文'.encode('utf-8')
Out:b'\xe4\xb8\xad\xe6\x96\x87'

這里的b就是Byte,\x表示這個x是被轉義的,意思就是0x。又如:

In: 'abc'.encode('utf-8')

Out: b'abc'

上面的b'a'其實表示的是數字97,b'a'的意思就是字元串'a'的binary數字:

[In]:'abc'.encode('utf-8')[0]

[Out]: 97

同時可以把b'\x'進行解碼,即:
In:b'\xe4\xb8\xad\xe6\x96\x87'.decode('utf-8')
Out:'中文'
除了encode('utf-8')外,用ord可以獲得單個utf-8字元對應的數字:

In [60]: ord('a')
Out[60]: 97
In [61]: ord('a')#這個是全形的a
Out[61]: 65345

除了decode('utf-8')外,用chr可以獲得數字對應的utf-8字元:

In [62]: chr(97)
Out[62]: 'a'

除了unicode還有別的編碼標准嗎?有啊,比如我國的GBK,別名也叫cp936。

全形和半形之分,是指同樣一個意義的字元,顯示的大小不同.具體來說,全形和半形的編碼是兩個結果:

In [70]: "mn".encode('utf-8')
Out[70]: b'\xef\xbd\x8d\xef\xbd\x8e
[In]:"mn".encode('utf-8')

[Out]:b'mn'

它們有什麼對應關系呢?(引自這里)

轉換說明
全形半形轉換說明
有規律(不含空格):
全形字元unicode編碼從65281~65374 (十六進制 0xFF01 ~ 0xFF5E)
半形字元unicode編碼從33~126 (十六進制 0x21~ 0x7E)
特例:
空格比較特殊,全形為 12288(0x3000),半形為 32(0x20)
除空格外,全形/半形按unicode編碼排序在順序上是對應的(半形 + 0x7e= 全形),所以可以直接通過用+-法來處理非空格數據,對空格單獨處理。
代碼在此基礎上改動一下(將unichr改為chr即可,適應python3),即:

def strQ2B(ustring):
"""全形轉半形"""
rstring = ""
for uchar in ustring:
inside_code=ord(uchar)
if inside_code == 12288: #全形空格直接轉換
inside_code = 32
elif (inside_code >= 65281 and inside_code <= 65374): #全形字元(除空格)根據關系轉化
inside_code -= 65248
rstring += chr(inside_code)
return rstring

In [69]: strQ2B('你好python')
Out[69]: '你好python'

Ⅲ 如何將全形字元轉換為半形字元

輸入法選定後,有個輸入狀態框,上面有個月亮表示半形字元,滑鼠左鍵單擊變成圓形,就是全形字元。還可以用shift+空格鍵轉換

Ⅳ 如何將打好的符號全形轉化為半形

按ctrl+f打開「查找和替換」對話框中的「查找」選項,勾選「突出顯示所有在該范圍找到的項目」,輸入查找內容:^$,查找任意字母,不區分字母的大小寫,單擊「查找全部」後,word將全選所選內容的所有字母,單擊「格式/更改大小寫」,選中「半形」,「確定」即可。
輸入查找內容:^#,查找任意數字,單擊「查找全部」後,word將全選所選內容的所有數字,單擊「格式/更改大小寫」,選中「半形」,「確定」即可。

閱讀全文

與python27全形轉半形相關的資料

熱點內容
android雲盤開發 瀏覽:963
139郵箱的發送伺服器地址 瀏覽:826
長沙銀行用什麼樣的APP 瀏覽:889
無憂推客源碼 瀏覽:461
怎樣用文件夾發微信上去 瀏覽:424
單片機movp1a什麼意思 瀏覽:577
plc編程龍門銑床 瀏覽:373
畢業做程序員好嗎 瀏覽:715
python最好的web框架 瀏覽:231
程序員同學玩騰訊 瀏覽:347
pdf掃描壓縮 瀏覽:164
程序員面試學歷太重要了 瀏覽:420
excel轉pdf不全 瀏覽:513
命令任務管理器 瀏覽:207
phparrayrecursive 瀏覽:712
天狼程序麻將機app怎麼下載 瀏覽:895
多行文字命令里怎麼弄每行三個字 瀏覽:558
方舟mod伺服器是什麼 瀏覽:990
怎麼下載智悲佛網的app 瀏覽:35
android地面站 瀏覽:486