Python Regular expression matching Chinese usage example

Source: Internet
Author: User
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:

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.