目录【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 datasum=0for score in data[1:]:print int(score)sum +=int(score)#print sumresult='%s\t:%d\n' %(data[0],sum)print resultresults.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+1print "a=%d" %aprint "sum=%s" %sumprint "从1连加到100的和为%s" %sum【Python 模块】while循环示例连加# -*- coding: cp936 -*-a=0sum=0while a<100:a+=1sum=sum+aprint "a=%d" %aprint "sum=%s" %sumprint "从1连加到100的和为%s" %sum【Python 模块】函数及判断示例def isEqual(num1,num2):if num1 < num2:print "too small"return False;elif 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 – excepts += "%e " % float(i) #将浮点数字格式化为自然数except:s += "%s " % i #将内容格式化为字符串print s.strip() #删除函数strip(rm),当rm为空时,默认删除空白符(包括'\n', '\r', '\t', ' ')【Python 模块】使用多个字符分割a='Beautiful, is; better*than\nugly'import 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='heaven'b='hell'c=True and a or bprint cd= False and a or bprint d【Python 模块】面向对象的类及示例class Car:speed=0def drive(self,distance):time = distance/self.speedprint 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 = speeddef 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 = fueldef 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 str1print# 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 wordlastchar = word1[-1:]# use a list of punctuation marksif lastchar in [",", ".", "!", "?", ";"]:word2 = word1.rstrip(lastchar)else:word2 = word1# build a wordList of lower case modified wordswordList2.append(word2.lower())print "Word list created from modified string:"print wordList2print# create a wordfrequency dictionary 字符统计模块,通过设置字典及字典的函数实现# start with an empty dictionaryfreqD2 = {}for word2 in wordList2:freqD2[word2] = 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, freqD2[key2])【Python 模块】网页访问数据获取示例import urllib2import jsoncitycode='101190101'url= ('/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()scores[s[0]] = s[1:]score = scores.get(name)if score is None:score = [0,0,0]#print scoregame_times=int(score[0])min_times=int(score[1])total_times=int(score[2])if game_times > 0:avg_times = float(total_times)/game_timeselse:avg_times = 0print '%s,你已经玩了%d次,最少%d轮猜出答案,平均%.2f轮猜出答案。