目录【Python模块】文件读入输出一................................................................................................1【Python模块】文件读入输出二................................................................................................1【Python模块】文件输入输出及拆分示例.................................................................................1【Python模块】for循环示例连加.............................................................................................2【Python模块】while循环示例连加.........................................................................................2【Python模块】函数及判断示例................................................................................................2【Python模块】文本拆分示例....................................................................................................3【Python模块】使用多个字符分割.............................................................................................3【Python模块】修剪字符串........................................................................................................3【Python模块】删除空行技巧....................................................................................................3【Python模块】andor技巧......................................................................................................4【Python模块】面向对象的类及示例.........................................................................................4【Python模块】子类与继承示例................................................................................................4【Python模块】字符统计实例....................................................................................................5【Python模块】网页访问数据获取示例.....................................................................................6【Python综合】猜游戏程序示例.................................................................................................6【Python模块】文件读入输出一f=file('tmp.txt')data=f.read()f.closeout=file('out.txt','w')out.write(data)out.close【Python模块】文件读入输出二data='\nIwillbeinafile.\nSocool!'out=open('output.txt','a')printdataout.write(data)out.close【Python模块】文件输入输出及拆分示例f=file('scores.txt')lines=f.readlines()#从文件中读取全部行f.closeprintlines;results=[]forlineinlines:#对每一行数据进行处理data=line.split()printdatasum=0forscoreindata[1:]:printint(score)sum+=int(score)#printsumresult='%s\t:%d\n'%(data[0],sum)printresultresults.append(result)printresultsoutput=file('result.txt','a')#打开文件,模式为附加output.writelines(results)#将数据写入文件附加在最后output.close()【Python模块】for循环示例连加sum=0forainrange(0,100):sum=sum+a+1printa=%d%aprintsum=%s%sumprint从1连加到100的和为%s%sum【Python模块】while循环示例连加#-*-coding:cp936-*-a=0sum=0whilea100:a+=1sum=sum+aprinta=%d%aprintsum=%s%sumprint从1连加到100的和为%s%sum【Python模块】函数及判断示例defisEqual(num1,num2):ifnum1num2:printtoosmallreturnFalse;elifnum1num2:printtoobigreturnFalse;else:printbingoreturnTruenum1=10num2=input()printisEqual(num1,num2)【Python模块】文本拆分示例line='abc123.4def9999ghi2.33's=''foriinline.split():try:#异常处理try–excepts+=%e%float(i)#将浮点数字格式化为自然数except:s+=%s%i#将内容格式化为字符串prints.strip()#删除函数strip(rm),当rm为空时,默认删除空白符(包括'\n','\r','\t','')【Python模块】使用多个字符分割a='Beautiful,is;better*than\nugly'importrere.split(';|,|\*|\n',a)#在’’之间的内容为分隔符,以|隔开运行结果:['Beautiful','is','better','than','ugly']【Python模块】修剪字符串b='(123)'printb.strip('()')#删除字符串中的“()”结果为:123【Python模块】删除空行技巧qfile=open('wq.txt','w').writelines([lforlinopen('ww.txt','r').readlines()ifl[:-1].strip()fl[:-1].strip()l是从旧文件里读出来的每一行,判断如果不是空行,则把这一行存到列表中,再将新的列表按行写入新文件。首先strip()是去除空白字符的意思。l[:-1].strip()是把这一行中除了最后那个换行符去掉,然后再去掉空白字符得到的字符串如果去掉换行符和空白符后得到的是空字符串的话,这一行就被抛弃,否则加入新的列表,等待写入。【Python模块】andor技巧#-*-coding:cp936-*-a='heaven'b='hell'c=Trueandaorbprintcd=Falseandaorbprintd【Python模块】面向对象的类及示例classCar:speed=0defdrive(self,distance):time=distance/self.speedprinttimecar=Car()car.speed=60.0car.drive(100.0)car1=Car()car1.speed=150.0car1.drive(100.0)car1.drive(200.0)car1.drive(300.0)【Python模块】子类与继承示例#-*-coding:cp936-*-classVehicle():def__init__(self,speed):#输入_init_时报错,必须两个下划线self.speed=speeddefdrive(self,distance):print'need%.1fhours'%(distance/self.speed)classBike(Vehicle):passclassCar(Vehicle):def__init__(self,speed,fuel):Vehicle.__init__(self,speed)self.fuel=fueldefdrive(self,distance):Vehicle.drive(self,distance)print'need%.1ffuels'%(distance*self.fuel)b=Bike(15.0)c=Car(80.0,0.012)b.drive(100.0)c.drive(100.0)【Python模块】字符统计实例#wordfrequencyinatext#testedwithPython24vegaseat25aug2005#Chinesewisdom...str1=Manwhoruninfrontofcar,gettired.Manwhorunbehindcar,getexhausted.printOriginalstring:printstr1print#createalistofwordsseparatedatwhitespaceswordList1=str1.split(None)#stripanypunctuationmarksandbuildmodifiedwordlist#startwithanemptylistwordList2=[]forword1inwordList1:#lastcharacterofeachwordlastchar=word1[-1:]#usealistofpunctuationmarksiflastcharin[,,.,!,?,;]:word2=word1.rstrip(lastchar)else:word2=word1#buildawordListoflowercasemodifiedwordswordList2.append(word2.lower())printWordlistcreatedfrommodifiedstring:printwordList2print#createawordfrequencydictionary字符统计模块,通过设置字典及字典的函数实现#startwithanemptydictionaryfreqD2={}forword2inwordList2:freqD2[word2]=fr