99999久久久久久亚洲,欧美人与禽猛交狂配,高清日韩av在线影院,一个人在线高清免费观看,啦啦啦在线视频免费观看www

熱線電話:13121318867

登錄
首頁(yè)精彩閱讀Python計(jì)算字符寬度的方法
Python計(jì)算字符寬度的方法
2018-02-09
收藏

Python計(jì)算字符寬度的方法

本文實(shí)例講述了Python計(jì)算字符寬度的方法。分享給大家供大家參考,具體如下:

最近在用python寫一個(gè)CLI小程序,其中涉及到計(jì)算字符寬度,目標(biāo)是以友好的方式將一個(gè)長(zhǎng)字符串截取為等寬的片段。

對(duì)于unicode字符,python的len函數(shù)可以準(zhǔn)確的計(jì)算其中所包含的字符個(gè)數(shù),但是個(gè)數(shù)并不代表寬度,如:   

>>>len(u'你好a')

3

因此無(wú)法簡(jiǎn)單的使用這種方式來(lái)計(jì)算寬度。

GBK decode

首先我想到GBK編碼,00–7F范圍內(nèi)的字符是一字節(jié)編碼,其余是雙字節(jié)編碼,正好與字符的寬度大體一致,于是有了這樣的投機(jī)取巧的辦法(假設(shè)取8個(gè)寬度):    
>>> a = u'hello你好'
>>> b=a.encode('gbk')
>>> try:
...  print b[:8].decode('gbk')
... except:
...  print b[:7].decode('gbk')
...
hello你

如代碼所示,首先將unicode的字符串進(jìn)行GBK編碼,然后截取8個(gè)字節(jié)的寬度后嘗試用GBK解碼,若解碼失敗,則少截取一個(gè)寬度,截取7個(gè)字節(jié)后使用GBK解碼。

雖然初步解決了問(wèn)題,但是這樣做的硬傷很明顯。首先代碼不優(yōu)雅,以試錯(cuò)的方式運(yùn)行;其次GBK所能表示的字符有限,對(duì)于大量GBK編碼以外的字符無(wú)法支持。

East_Asian_Width

徘徊很久之后,偶然發(fā)現(xiàn) Unicode Character Database 標(biāo)準(zhǔn)中有East_Asian_Width 屬性,并有以下可能值:    
# East_Asian_Width (ea)
ea ; A     ; Ambiguous  不確定
ea ; F     ; Fullwidth  全寬
ea ; H     ; Halfwidth  半寬
ea ; N     ; Neutral   中性
ea ; Na    ; Narrow    窄
ea ; W     ; Wide     寬

其中除A不確定外,F(xiàn)/H/N/Na/W都能很明確的知道寬度,如果保守起見(jiàn),將A視為寬度為2的話,則很容易給出單個(gè)字符的寬度:    
>>> import unicodedata
>>> def chr_width(c):
...  if (unicodedata.east_asian_width(c) in ('F','W','A')):
...   return 2
...  else:
...   return 1
>>> chr_width(u'你')
2
>>> chr_width(u'a')
1

到現(xiàn)在似乎已經(jīng)可以滿足要求了,但是實(shí)際使用中發(fā)現(xiàn)屬性為A的字符真不少見(jiàn),最典型的就是中文的雙引號(hào):
    
>>> chr_width(u'”')
2

在大多數(shù)等寬字體中,中文雙引號(hào)都是只占一位寬的,如果一行里有多個(gè)中文雙引號(hào),則累加的誤判寬度將會(huì)使截取效果大打折扣,無(wú)疑這也不是最好的辦法。

urwid的解決方案

urwid  是一個(gè)成熟的python終端UI庫(kù),它在curses的基礎(chǔ)之上包裝了類似HTML的控件用以顯示文本內(nèi)容,如果有這方面的開(kāi)發(fā)需求,非常推薦此庫(kù),比直接使用curses庫(kù)方便很多,非常棒的是它對(duì)unicode的文本寬度截取非常準(zhǔn)確,讓我大為驚訝,于是翻開(kāi)它的源碼一探究竟,文本寬度計(jì)算方面其核心代碼如下:    
widths = [
  (126,  1), (159,  0), (687,   1), (710,  0), (711,  1),
  (727,  0), (733,  1), (879,   0), (1154, 1), (1161, 0),
  (4347,  1), (4447,  2), (7467,  1), (7521, 0), (8369, 1),
  (8426,  0), (9000,  1), (9002,  2), (11021, 1), (12350, 2),
  (12351, 1), (12438, 2), (12442,  0), (19893, 2), (19967, 1),
  (55203, 2), (63743, 1), (64106,  2), (65039, 1), (65059, 0),
  (65131, 2), (65279, 1), (65376,  2), (65500, 1), (65510, 2),
  (120831, 1), (262141, 2), (1114109, 1),
]
def get_width( o ):
  """Return the screen column width for unicode ordinal o."""
  global widths
  if o == 0xe or o == 0xf:
    return 0
  for num, wid in widths:
    if o <= num:
      return wid
  return 1

如代碼所示,首先根據(jù)unicode的官方EastAsianWidth  文檔整理出字符寬度的范圍表,然后使用unicode代碼查表。使用之前的例子測(cè)試:    
>>> get_width(ord(u'a'))
1
>>> get_width(ord(u'你'))
2
>>> get_width(ord(u'”'))
1
完全準(zhǔn)確,而且在實(shí)際應(yīng)用中的表現(xiàn)也比較好,是一個(gè)理想的解決方案,更多技巧請(qǐng)查閱urwid的old_str_util.py 源碼。

數(shù)據(jù)分析咨詢請(qǐng)掃描二維碼

若不方便掃碼,搜微信號(hào):CDAshujufenxi

數(shù)據(jù)分析師資訊
更多

OK
客服在線
立即咨詢
客服在線
立即咨詢
') } function initGt() { var handler = function (captchaObj) { captchaObj.appendTo('#captcha'); captchaObj.onReady(function () { $("#wait").hide(); }).onSuccess(function(){ $('.getcheckcode').removeClass('dis'); $('.getcheckcode').trigger('click'); }); window.captchaObj = captchaObj; }; $('#captcha').show(); $.ajax({ url: "/login/gtstart?t=" + (new Date()).getTime(), // 加隨機(jī)數(shù)防止緩存 type: "get", dataType: "json", success: function (data) { $('#text').hide(); $('#wait').show(); // 調(diào)用 initGeetest 進(jìn)行初始化 // 參數(shù)1:配置參數(shù) // 參數(shù)2:回調(diào),回調(diào)的第一個(gè)參數(shù)驗(yàn)證碼對(duì)象,之后可以使用它調(diào)用相應(yīng)的接口 initGeetest({ // 以下 4 個(gè)配置參數(shù)為必須,不能缺少 gt: data.gt, challenge: data.challenge, offline: !data.success, // 表示用戶后臺(tái)檢測(cè)極驗(yàn)服務(wù)器是否宕機(jī) new_captcha: data.new_captcha, // 用于宕機(jī)時(shí)表示是新驗(yàn)證碼的宕機(jī) product: "float", // 產(chǎn)品形式,包括:float,popup width: "280px", https: true // 更多配置參數(shù)說(shuō)明請(qǐng)參見(jiàn):http://docs.geetest.com/install/client/web-front/ }, handler); } }); } function codeCutdown() { if(_wait == 0){ //倒計(jì)時(shí)完成 $(".getcheckcode").removeClass('dis').html("重新獲取"); }else{ $(".getcheckcode").addClass('dis').html("重新獲取("+_wait+"s)"); _wait--; setTimeout(function () { codeCutdown(); },1000); } } function inputValidate(ele,telInput) { var oInput = ele; var inputVal = oInput.val(); var oType = ele.attr('data-type'); var oEtag = $('#etag').val(); var oErr = oInput.closest('.form_box').next('.err_txt'); var empTxt = '請(qǐng)輸入'+oInput.attr('placeholder')+'!'; var errTxt = '請(qǐng)輸入正確的'+oInput.attr('placeholder')+'!'; var pattern; if(inputVal==""){ if(!telInput){ errFun(oErr,empTxt); } return false; }else { switch (oType){ case 'login_mobile': pattern = /^1[3456789]\d{9}$/; if(inputVal.length==11) { $.ajax({ url: '/login/checkmobile', type: "post", dataType: "json", data: { mobile: inputVal, etag: oEtag, page_ur: window.location.href, page_referer: document.referrer }, success: function (data) { } }); } break; case 'login_yzm': pattern = /^\d{6}$/; break; } if(oType=='login_mobile'){ } if(!!validateFun(pattern,inputVal)){ errFun(oErr,'') if(telInput){ $('.getcheckcode').removeClass('dis'); } }else { if(!telInput) { errFun(oErr, errTxt); }else { $('.getcheckcode').addClass('dis'); } return false; } } return true; } function errFun(obj,msg) { obj.html(msg); if(msg==''){ $('.login_submit').removeClass('dis'); }else { $('.login_submit').addClass('dis'); } } function validateFun(pat,val) { return pat.test(val); }