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

熱線電話:13121318867

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

Python計算字符寬度的方法

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

最近在用python寫一個CLI小程序,其中涉及到計算字符寬度,目標是以友好的方式將一個長字符串截取為等寬的片段。

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

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

3

因此無法簡單的使用這種方式來計算寬度。

GBK decode

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

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

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

East_Asian_Width

徘徊很久之后,偶然發(fā)現(xiàn) Unicode Character Database 標準中有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都能很明確的知道寬度,如果保守起見,將A視為寬度為2的話,則很容易給出單個字符的寬度:    
>>> 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)可以滿足要求了,但是實際使用中發(fā)現(xiàn)屬性為A的字符真不少見,最典型的就是中文的雙引號:
    
>>> chr_width(u'”')
2

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

urwid的解決方案

urwid  是一個成熟的python終端UI庫,它在curses的基礎(chǔ)之上包裝了類似HTML的控件用以顯示文本內(nèi)容,如果有這方面的開發(fā)需求,非常推薦此庫,比直接使用curses庫方便很多,非常棒的是它對unicode的文本寬度截取非常準確,讓我大為驚訝,于是翻開它的源碼一探究竟,文本寬度計算方面其核心代碼如下:    
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代碼查表。使用之前的例子測試:    
>>> get_width(ord(u'a'))
1
>>> get_width(ord(u'你'))
2
>>> get_width(ord(u'”'))
1
完全準確,而且在實際應用中的表現(xiàn)也比較好,是一個理想的解決方案,更多技巧請查閱urwid的old_str_util.py 源碼。

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

若不方便掃碼,搜微信號: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(), // 加隨機數(shù)防止緩存 type: "get", dataType: "json", success: function (data) { $('#text').hide(); $('#wait').show(); // 調(diào)用 initGeetest 進行初始化 // 參數(shù)1:配置參數(shù) // 參數(shù)2:回調(diào),回調(diào)的第一個參數(shù)驗證碼對象,之后可以使用它調(diào)用相應的接口 initGeetest({ // 以下 4 個配置參數(shù)為必須,不能缺少 gt: data.gt, challenge: data.challenge, offline: !data.success, // 表示用戶后臺檢測極驗服務器是否宕機 new_captcha: data.new_captcha, // 用于宕機時表示是新驗證碼的宕機 product: "float", // 產(chǎn)品形式,包括:float,popup width: "280px", https: true // 更多配置參數(shù)說明請參見:http://docs.geetest.com/install/client/web-front/ }, handler); } }); } function codeCutdown() { if(_wait == 0){ //倒計時完成 $(".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 = '請輸入'+oInput.attr('placeholder')+'!'; var errTxt = '請輸入正確的'+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); }