Python2.7处理文本常用代码模块.doc_第1页
Python2.7处理文本常用代码模块.doc_第2页
Python2.7处理文本常用代码模块.doc_第3页
Python2.7处理文本常用代码模块.doc_第4页
Python2.7处理文本常用代码模块.doc_第5页
已阅读5页,还剩3页未读 继续免费阅读

下载本文档

版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领

文档简介

目录【Python 模块】文件读入输出一1【Python 模块】文件读入输出二1【Python 模块】文件输入输出及拆分示例1【Python 模块】for循环示例连加2【Python 模块】while循环示例连加2【Python 模块】函数及判断示例2【Python 模块】文本拆分示例3【Python 模块】使用多个字符分割3【Python 模块】修剪字符串3【Python 模块】删除空行技巧3【Python 模块】and or 技巧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=nI will be in a file.nSo cool!out =open(output.txt,a)print dataout.write(data)out.close【Python 模块】文件输入输出及拆分示例f = file(scores.txt)lines=f.readlines() #从文件中读取全部行f.closeprint lines;results=for line in lines: #对每一行数据进行处理 data = line.split() print data sum=0 for score in data1: print int(score) sum +=int(score) #print sum result=%st:%dn %(data0,sum) print result results.append(result) print resultsoutput=file(result.txt,a) #打开文件,模式为附加output.writelines(results) #将数据写入文件附加在最后output.close()【Python 模块】for循环示例连加sum=0for a in range(0,100): sum=sum+a+1 print a=%d %a print sum=%s %sumprint 从1连加到100的和为%s %sum【Python 模块】while循环示例连加# -*- coding: cp936 -*-a=0sum=0while a100: a+=1 sum=sum+a print a=%d %a print sum=%s %sumprint 从1连加到100的和为%s %sum【Python 模块】函数及判断示例def isEqual(num1,num2): if num1 num2: print too big return False; else: print bingo return Truenum1=10num2=input()print isEqual(num1,num2)【Python 模块】文本拆分示例line = abc 123.4 def 9999 ghi 2.33 s = for i in line.split(): try: #异常处理try except s += %e % float(i) #将浮点数字格式化为自然数 except: s += %s % i #将内容格式化为字符串print s.strip() #删除函数strip(rm),当rm为空时,默认删除空白符(包括n, r, t, )【Python 模块】使用多个字符分割a=Beautiful, is; better*thannuglyimport rere.split(; |, |*|n,a) #在之间的内容为分隔符,以|隔开运行结果:Beautiful, is, better, than, ugly【Python 模块】修剪字符串b = (123)print b.strip() #删除字符串中的“()”结果为:123【Python 模块】删除空行技巧qfile = open(wq.txt,w).writelines(l for l in open(ww.txt,r).readlines() if l:-1.strip()f l:-1.strip()l是从旧文件里读出来的每一行,判断如果不是空行,则把这一行存到列表中,再将新的列表按行写入新文件。首先strip()是去除空白字符的意思。l:-1.strip()是把这一行中除了最后那个换行符去掉,然后再去掉空白字符得到的字符串如果去掉换行符和空白符后得到的是空字符串的话,这一行就被抛弃,否则加入新的列表,等待写入。【Python 模块】and or 技巧# -*- coding: cp936 -*-a=heavenb=hellc=True and a or bprint cd= False and a or bprint d【Python 模块】面向对象的类及示例class Car: speed=0 def drive(self,distance): time = distance/self.speed print timecar = 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 -*-class Vehicle(): def _init_(self,speed): #输入_init_时报错,必须两个下划线 self.speed = speed def drive(self,distance): print need %.1f hours %(distance/self.speed)class Bike(Vehicle): passclass Car(Vehicle): def _init_(self,speed,fuel): Vehicle._init_(self,speed) self.fuel = fuel def drive(self,distance): Vehicle.drive(self,distance) print need %.1f fuels %(distance*self.fuel)b=Bike(15.0)c=Car(80.0,0.012)b.drive(100.0)c.drive(100.0)【Python 模块】字符统计实例# word frequency in a text# tested with Python24 vegaseat 25aug2005 # Chinese wisdom .str1 = Man who run in front of car, get tired.Man who run behind car, get exhausted.print Original string:print str1 print # create a list of words separated at whitespaceswordList1 = str1.split(None) # strip any punctuation marks and build modified word list# start with an empty listwordList2 = for word1 in wordList1: # last character of each word lastchar = word1-1: # use a list of punctuation marks if lastchar in , ., !, ?, ;: word2 = word1.rstrip(lastchar) else: word2 = word1 # build a wordList of lower case modified words wordList2.append(word2.lower() print Word list created from modified string:print wordList2 print # create a wordfrequency dictionary 字符统计模块,通过设置字典及字典的函数实现# start with an empty dictionaryfreqD2 = for word2 in wordList2: freqD2word2 = freqD2.get(word2, 0) + 1 #为字典赋值,键和值,值累加 # create a list of keys and sort the list# all words are lower case alreadykeyList = freqD2.keys()keyList.sort() print Frequency of each word in the word list (sorted):for key2 in keyList: print %-10s %d % (key2, freqD2key2)【Python 模块】网页访问数据获取示例import urllib2import jsoncitycode=101190101url= (/data/cityinfo/%s.html%citycode)content = urllib2.urlopen(url).read()print content结果 weatherinfo:city:南京,cityid:101190101,temp1:15,temp2:10,weather:小雨,img1:d7.gif,img2:n7.gif,ptime:08:00【Python综合】猜游戏程序示例# -*- coding: cp936 -*-from random import randintname = raw_input(请输入你的名字:) #3.4版本和input整合了,在input后面需要使用()f=open(d:/Python27/MyProject/20150318/game.txt)lines = f.readlines()f.close()scores = for l in lines: s = l.split() scoress0 = s1:score = scores.get(name)if score is None: score = 0,0,0#print score game_times=int(score0)min_times=int(score1)total_times=int(score2)if game_times 0: avg_times = float(total_times)/game_timeselse: avg_times = 0print %s,你已经玩了%d次,最少%d轮猜出答案,平均%.2f轮猜出答案。 %(name,game_times,min_times,avg_times)num = randint(1,100)times = 0print 猜猜我是几?bingo = Falsewhile bingo = False: times += 1 answer = input() if answer num: print 太大了! if answer = num: print 猜对了! bingo = True #如果是第一次玩,或者轮数比最小轮还少,则更新轮数。if game_times = 0 or times min_times: min_times = times total_times += times#print total_timesgame_times +=1#把成绩更新到对应的玩家数据中#加str转成字符串,为后面的格式化做准备scoresname = str(game_times),str(min_times),str(total_times)result = for n in scores: #sco

温馨提示

  • 1. 本站所有资源如无特殊说明,都需要本地电脑安装OFFICE2007和PDF阅读器。图纸软件为CAD,CAXA,PROE,UG,SolidWorks等.压缩文件请下载最新的WinRAR软件解压。
  • 2. 本站的文档不包含任何第三方提供的附件图纸等,如果需要附件,请联系上传者。文件的所有权益归上传用户所有。
  • 3. 本站RAR压缩包中若带图纸,网页内容里面会有图纸预览,若没有图纸预览就没有图纸。
  • 4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
  • 5. 人人文库网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对用户上传分享的文档内容本身不做任何修改或编辑,并不能对任何下载内容负责。
  • 6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
  • 7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。

评论

0/150

提交评论