This example describes the Python regular expression matching Chinese usage. Share to everyone for your reference, as follows:
#!/usr/bin/python#-*-coding:cp936-*-#思路, the STR is converted to Unicode, the regular expression can be used, if you want to know the encoding of the file, in this case Gbkimport Cpickle as Mypickleimport reimport sysif (__name__== ' __main__ '): Fid1=file (' Demo.txt ', ' R '); #demo. txt write word such as: script House P=re.compile (' ( ^\s+|\s+$) '); Phanzigbk=re.compile (' [\\x20-\\x7f] '); Phanzi=re.compile (U ' [\u4e00-\u9fa5] '); #这里要加u, note commlines=fid1.readlines (); Fid1.close (); dictfamilyname={}; dictfirstname={}; For line in Commlines:line=p.sub (", line); Print type (line); Print line; Uline=unicode (line, ' GBK '); Print type (uline); Candidates=phanzi.findall (Uline); Print len (candidates); if (Len (candidates) ==2): Print candidates[0]; Familynamegbk=candidates[0].encode (' GBK '); #把unicode型的变量变成str型的变量 firstnamegbk=candidates[1].encode (' GBK '); if (Dictfamilyname.has_key (FAMILYNAMEGBK)): dictfamilyname[familynamegbk]=dictfamilyname[familynamegbk]+1; Else:dictfamilyname[familynamegbk]=1; if (Dictfirstname.has_key (FIRSTNAMEGBK)): DICtfirstname[firstnamegbk]=dictfirstname[firstnamegbk]+1; Else:dictfirstname[firstnamegbk]=1; Familynameitems=dictfamilyname.items (); Print Familynameitems; Firstnameitems=dictfirstname.items (); Familynameitems.sort (Key=lambda d:d[1],reverse=true); Firstnameitems.sort (Key=lambda d:d [1],reverse=true); Fid=file (' Familyname.txt ', ' W '); For m in familynameitems:s=m[0]+ ' \ t ' +str (m[1]); Fid.write (s); Fid.write (' \ n '); Fid.close (); Fid=file (' Firstname.txt ', ' W '); For m in firstnameitems:s=m[0]+ ' \ t ' +str (m[1]); Fid.write (s); Fid.write (' \ n '); Fid.close (); print ' Finish '
Run as follows: