资源预览内容
第1页 / 共6页
第2页 / 共6页
第3页 / 共6页
第4页 / 共6页
第5页 / 共6页
第6页 / 共6页
亲,该文档总共6页全部预览完了,如果喜欢就下载吧!
资源描述
1. 判断字符串中是否含有汉字。def has_hz(text): hz_yes = False for ch in text: if isinstance(ch, unicode): if unicodedata.east_asian_width(ch)!= Na: hz_yes = True break else: continue return hz_yesdef has_hz(text): hz_yes = False for ch in text: if isinstance(ch, unicode): if unicodedata.east_asian_width(ch)!= Na: hz_yes = True break else: continue return hz_yes 单元测试: assert not has_hz() assert not has_hz( ) assert not has_hz(123) assert not has_hz(u123abc) assert has_hz(u123abc汉字) assert has_hz(u汉字) assert not has_hz() assert not has_hz( ) assert not has_hz(123) assert not has_hz(u123abc) assert has_hz(u123abc汉字) assert has_hz(u汉字)2. 隔指定长度插入一个换行符(/n),一个汉字算2个字符长def get_hz_string_width(text): 获取可能包含汉字的字符串的长度(1个汉字算2个字符长) s = 0 for ch in text: if isinstance(ch, unicode): if unicodedata.east_asian_width(ch)!= Na: s += 2 else: s += 1 else: s += 1 return sdef get_hz_sub_string(text,startat,sub_len=None): 获取可能包含汉字的字符串的子串(计算长度时,1个汉字算2个字符长) 用法: get_hz_sub_string(record,0,44) #取子串,位置为0至43 get_hz_sub_string(record,44) #取子串,位置为44至末尾 s = pos = 0 for ch in text: if pos = startat: s.append(ch) if isinstance(ch, unicode): if unicodedata.east_asian_width(ch)!= Na: pos += 2 else: pos += 1 else: pos += 1 if sub_len!=None and get_hz_string_width(.join(s)=sub_len: break return .join(s)def insert_line_feed(my_str,interval,line_feed=n): 隔指定长度插入一个n符号(一个汉字处理为2个字符长度) if len(my_str)=0: return n = int(get_hz_string_width(my_str)-1)/interval)+1 str_list = k = 1 pos_start = 0 while k = startat: s.append(ch) if isinstance(ch, unicode): if unicodedata.east_asian_width(ch)!= Na: pos += 2 else: pos += 1 else: pos += 1 if sub_len!=None and get_hz_string_width(.join(s)=sub_len: break return .join(s)def insert_line_feed(my_str,interval,line_feed=/n): 隔指定长度插入一个/n符号(一个汉字处理为2个字符长度) if len(my_str)=0: return n = int(get_hz_string_width(my_str)-1)/interval)+1 str_list = k = 1 pos_start = 0 while k 0: line_str = str_listi if len(line_st
收藏 下载该资源
网站客服QQ:2055934822
金锄头文库版权所有
经营许可证:蜀ICP备13022795号 | 川公网安备 51140202000112号