资源描述:
《python 判断字符串中是否含有汉字.doc》由会员上传分享,免费在线阅读,更多相关内容在教育资源-天天文库。
1、1.判断字符串中是否含有汉字。defhas_hz(text):hz_yes=Falseforchintext:ifisinstance(ch,unicode):ifunicodedata.east_asian_width(ch)!='Na':hz_yes=Truebreakelse:continuereturnhz_yesdefhas_hz(text):hz_yes=Falseforchintext:ifisinstance(ch,unicode):ifunicodedata.east_asian_width(ch)!=
2、'Na':hz_yes=Truebreakelse:continuereturnhz_yes单元测试:assertnothas_hz("")assertnothas_hz("")assertnothas_hz("123")assertnothas_hz(u"123abc")asserthas_hz(u"123abc汉字")asserthas_hz(u"汉字")assertnothas_hz("")assertnothas_hz("")assertnothas_hz("123")assertnothas_hz(u"123a
3、bc")asserthas_hz(u"123abc汉字")asserthas_hz(u"汉字")2.隔指定长度插入一个换行符(/n),一个汉字算2个字符长defget_hz_string_width(text):"""获取可能包含汉字的字符串的长度(1个汉字算2个字符长)"""s=0forchintext:ifisinstance(ch,unicode):ifunicodedata.east_asian_width(ch)!='Na':s+=2else:s+=1else:s+=1returnsdefget_hz_sub_
4、string(text,startat,sub_len=None):"""获取可能包含汉字的字符串的子串(计算长度时,1个汉字算2个字符长)用法:get_hz_sub_string(record,0,44)#取子串,位置为0至43get_hz_sub_string(record,44)#取子串,位置为44至末尾"""s=[]pos=0forchintext:ifpos>=startat:s.append(ch)ifisinstance(ch,unicode):ifunicodedata.east_asian_width(
5、ch)!='Na':pos+=2else:pos+=1else:pos+=1ifsub_len!=Noneandget_hz_string_width(''.join(s))>=sub_len:breakreturn''.join(s)definsert_line_feed(my_str,interval,line_feed=""):"""隔指定长度插入一个符号(一个汉字处理为2个字符长度)"""iflen(my_str)==0:return""n=int((get_hz_string_width(my_str)
6、-1)/interval)+1str_list=[]k=1pos_start=0whilek<=n:sub_str=get_hz_sub_string(my_str,pos_start,interval)str_list.append(sub_str)k=k+1pos_start=pos_start+get_hz_string_width(sub_str)returnline_feed.join(str_list)defget_hz_string_width(text):"""获取可能包含汉字的字符串的长度(1个汉字算2
7、个字符长)"""s=0forchintext:ifisinstance(ch,unicode):ifunicodedata.east_asian_width(ch)!='Na':s+=2else:s+=1else:s+=1returnsdefget_hz_sub_string(text,startat,sub_len=None):"""获取可能包含汉字的字符串的子串(计算长度时,1个汉字算2个字符长)用法:get_hz_sub_string(record,0,44)#取子串,位置为0至43get_hz_sub_strin
8、g(record,44)#取子串,位置为44至末尾"""s=[]pos=0forchintext:ifpos>=startat:s.append(ch)ifisinstance(ch,unicode):ifunicodedata.east_asian_width(ch)!='Na':pos+=2else:pos+=1