python 判断字符串中是否含有汉字.doc

上传人:M****1 文档编号:544015749 上传时间:2024-01-01 格式:DOC 页数:6 大小:49.01KB
返回 下载 相关 举报
python 判断字符串中是否含有汉字.doc_第1页
第1页 / 共6页
python 判断字符串中是否含有汉字.doc_第2页
第2页 / 共6页
python 判断字符串中是否含有汉字.doc_第3页
第3页 / 共6页
python 判断字符串中是否含有汉字.doc_第4页
第4页 / 共6页
python 判断字符串中是否含有汉字.doc_第5页
第5页 / 共6页
点击查看更多>>
资源描述

《python 判断字符串中是否含有汉字.doc》由会员分享,可在线阅读,更多相关《python 判断字符串中是否含有汉字.doc(6页珍藏版)》请在金锄头文库上搜索。

1、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

2、: 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(u12

3、3abc汉字) 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): 获取

4、可能包含汉字的字符串的子串(计算长度时,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_le

5、n!=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 isinstan

6、ce(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

展开阅读全文
相关资源
正为您匹配相似的精品文档
相关搜索

最新文档


当前位置:首页 > 生活休闲 > 社会民生

电脑版 |金锄头文库版权所有
经营许可证:蜀ICP备13022795号 | 川公网安备 51140202000112号