【Python进阶】02、文本处理与IO深入理解,,1、有一个文件,单词


1、有一个文件,单词之间使用空格、分号、逗号、或者句号分隔,请提取全部单词。

解决方案:

使用\w匹配并提取单词,但是存在误判

使用str.split分隔字符字符串,但是需要多次分隔

使用re.split分隔字符串

In[4]:help(re.split)Helponfunctionsplitinmodulere:split(pattern,string,maxsplit=0,flags=0)Splitthesourcestringbytheoccurrencesofthepattern,returningalistcontainingtheresultingsubstrings.
In[23]:text="i‘mxj,ilovePython,,Linux;idon‘tlikewindows."In[24]:fs=re.split(r"(,|\.|;|\s)+\s*",text)In[25]:fsOut[25]:["i‘m",‘‘,‘xj‘,‘‘,‘i‘,‘‘,‘love‘,‘‘,‘Python‘,‘,‘,‘Linux‘,‘‘,‘i‘,‘‘,"don‘t",‘‘,‘like‘,‘‘,‘windows‘,‘.‘,‘‘]In[26]:fs[::2]#提取出单词Out[26]:["i‘m",‘xj‘,‘i‘,‘love‘,‘Python‘,‘Linux‘,‘i‘,"don‘t",‘like‘,‘windows‘,‘‘]In[27]:fs[1::2]#提取出符号Out[27]:[‘‘,‘‘,‘‘,‘‘,‘,‘,‘‘,‘‘,‘‘,‘‘,‘.‘]In[53]:fs=re.findall(r"[^,\.;\s]+",text)In[54]:fsOut[54]:["i‘m",‘xj‘,‘i‘,‘love‘,‘Python‘,‘Linux‘,‘i‘,"don‘t",‘like‘,‘windows‘]In[55]:fh=re.findall(r‘[,\.;\s]‘,text)In[56]:fhOut[56]:[‘‘,‘,‘,‘‘,‘‘,‘‘,‘,‘,‘,‘,‘;‘,‘‘,‘‘,‘‘,‘‘,‘.‘]

2、有一个目录,保存了若干文件,找出其中所有的C源文件(.c和.h)

解决方案:

使用listdir

使用str.endswith判断

In[13]:s="xj.c"In[14]:s.endswith(".c")Out[14]:TrueIn[15]:s.endswith(".h")Out[15]:FalseIn[16]:importosIn[17]:os.listdir("/usr/include/")Out[17]:[‘libmng.h‘,‘netipx‘,‘ft2build.h‘,‘FlexLexer.h‘,‘selinux‘,‘QtSql‘,‘resolv.h‘,‘gio-unix-2.0‘,‘wctype.h‘,‘python2.6‘,‘scsi‘,...‘QtOpenGL‘,‘mysql‘,‘byteswap.h‘,,‘xj.c‘‘mntent.h‘,‘semaphore.h‘,‘stdio_ext.h‘,‘libxml2‘]In[21]:forfilenameinos.listdir("/usr/include"):iffilename.endswith(".c"):printfilename....:xj.cIn[22]:forfilenameinos.listdir("/usr/include"):iffilename.endswith((".c",".h")):#这里元祖是或的关系printfilename....:libmng.hft2build.hFlexLexer.hnss.hpng.hutime.hieee754.hfeatures.hxj.c...verto-module.hsemaphore.hstdio_ext.hIn[23]:


3、fnmath模块

支持和shell一样的通配符

In[24]:help(fnmatch)#是否区分大小写与操作系统一致Helponfunctionfnmatchinmodulefnmatch:fnmatch(name,pat)TestwhetherFILENAMEmatchesPATTERN.PatternsareUnixshellstyle:*matcheseverything?matchesanysinglecharacter[seq]matchesanycharacterinseq[!seq]matchesanycharnotinseqAninitialperiodinFILENAMEisnotspecial.BothFILENAMEandPATTERNarefirstcase-normalizediftheoperatingsystemrequiresit.Ifyoudon‘twantthis,usefnmatchcase(FILENAME,PATTERN).~(END)In[47]:fnmatch.fnmatch("sba.txt","*txt")Out[47]:TrueIn[48]:fnmatch.fnmatch("sba.txt","*t")Out[48]:TrueIn[49]:fnmatch.fnmatch("sba.txt","*b")Out[49]:FalseIn[50]:fnmatch.fnmatch("sba.txt","*b*")Out[50]:True

案例:你有一个程序处理文件,文件名由用户输入,你需要支持和shell一样的通配符。

[root@Node3src]#cattest1.py#!/usr/local/bin/python2.7#coding:utf-8importosimportsysfromfnmatchimportfnmatchret=[namefornameinos.listdir(sys.argv[1])iffnmatch(name,sys.argv[2])]printret[root@Node3src]#python2.7test1.py/usr/include/*.c[‘xj.c‘]


4、re.sub() 文本替换

In[53]:help(re.sub)Helponfunctionsubinmodulere:sub(pattern,repl,string,count=0,flags=0)Returnthestringobtainedbyreplacingtheleftmostnon-overlappingoccurrencesofthepatterninstringbythereplacementrepl.replcanbeeitherastringoracallable;ifastring,backslashescapesinitareprocessed.Ifitisacallable,it‘spassedthematchobjectandmustreturnareplacementstringtobeused.

案例:有一个文本,文本里的日期使用的是%m/%d/%Y的格式,你需要把它全部转化成%Y-%m-%d的格式。

In[55]:text="Todayis11/08/2016,nextclasstime11/15/2016"In[56]:new_text=re.sub(r‘(\d+)/(\d+)/(\d+)‘,r‘\3-\2-\1‘,text)In[57]:new_textOut[57]:‘Todayis2016-08-11,nextclasstime2016-15-11‘


5、str.format字符串格式化

案例:你需要创建一个小型的模版引擎,不需要逻辑控制,但是需要使用变量来填充模版

In[71]:help(str.format)Helponmethod_descriptor:format(...)S.format(*args,**kwargs)->stringReturnaformattedversionofS,usingsubstitutionsfromargsandkwargs.Thesubstitutionsareidentifiedbybraces(‘{‘and‘}‘).(END)




本文出自 “xiexiaojun” 博客,请务必保留此出处http://xiexiaojun.blog.51cto.com/2305291/1870832

【Python进阶】02、文本处理与IO深入理解

相关内容

    暂无相关文章

评论关闭