Python笔记
#coding:utf-8 a = raw_input() try: if int(a) > 0: print '输入为正数' elif int(a) < 0: print '输入为负数' else: print '输入为0' except Exception,e: print '请输入数字'
抓取异常,Python缩进格式要求严格,与Java不同,可以理解Python中的缩进格式与Java的{}相当
# coding:utf-8 i = 0 a = [] for i in range(3): print '请输入数字:' b = raw_input() a.append(b) if float(b) > 100: print b, '请输入1到100的整数', a elif float(b) < 0: print b, '请输入1到100的正整数', a else: print b, '符合要求' break else: print '输入次数超出!' # a = [1.0, 2.3, 3.3] try: print '输入字符长度为:', len(a) i = 0 b = 0 while i in range(len(a)): print '第', i, '个字为', a[i] b += float(a[i]) i += 1 c = b / len(a) print '平均值为:', c except Exception: print '请输入正确内容'
Python循环跳出使用break
新建文件并输入文件内容
#!/usr/bin/env python # coding:utf-8 'makeTextFile.py -- create text file' import os ls = os.linesep print ls # get filename while True: fname = raw_input('请输入文件名:') if os.path.exists(fname): print "ERROR: '%s' already exists" % fname else: break # get file content (text) lines all = [] print "\nEnter lines (输入'.'结束).\n" # loop until user terminates input i = 1 while i > 0: print '输入第', i, '行' entry = raw_input() i += 1 if entry == '.': break else: all.append(entry) # write lines to file with proper line-ending fobj = open(fname, 'w') fobj.writelines(['%s%s' % (x, ls) for x in all]) fobj.close() print 'DONE!'
文件读取
1 #!/usr/bin/env Python 2 # coding:utf-8 3 'readFile.py--read and display' 4 # get filename 5 6 # attempt to open file for reading 7 while True: 8 fname = raw_input('Enter filename:') 9 print 10 try: 11 fobj = open(fname, 'r') 12 except IOError, e: 13 print '文件读取错误', e 14 else: 15 # display contents in fobj: 16 for eachLine in fobj: 17 print eachLine, 18 fobj.close() 19 break
选择功能
1 #!/usr/bin/env python 2 # coding:utf-8 3 'makeTextFile.py -- create text file' 4 5 import os 6 7 ls = os.linesep 8 print ls 9 # get filename 10 # 选择功能 11 while True: 12 type = int(raw_input('请输入功能类型:1为创建文件,2为读取文件,输入0退出程序:')) 13 if type == 1: 14 while True: 15 fname = raw_input('请输入文件名:') 16 if os.path.exists(fname): 17 print "ERROR: '%s' already exists" % fname 18 else: 19 break 20 21 # get file content (text) lines 22 all = [] 23 print "\nEnter lines (输入'.'结束).\n" 24 25 # loop until user terminates input 26 i = 1 27 while i > 0: 28 print '输入第', i, '行' 29 entry = raw_input() 30 i += 1 31 if entry == '.': 32 break 33 else: 34 all.append(entry) 35 # write lines to file with proper line-ending 36 fobj = open(fname, 'w') 37 fobj.writelines(['%s%s' % (x, ls) for x in all]) 38 fobj.close() 39 print 'DONE!' 40 elif type == 2: 41 'readFile.py--read and display' 42 # get filename 43 44 # attempt to open file for reading 45 while True: 46 fname = raw_input('Enter filename:') 47 print 48 try: 49 fobj = open(fname, 'r') 50 except IOError, e: 51 print '读取该文件名错误', e 52 else: 53 # display contents in fobj: 54 for eachLine in fobj: 55 print eachLine.strip(), # 去除每行末尾空白 56 fobj.close() 57 break 58 elif type == 0: 59 break 60 else: 61 print '请输入正确内容'
*Python参数定义顺序必须是:必填参数,默认参数,可变参数,关键字参数
*args 是可变参数,args接收的是一个tuple元祖
**kw 是关键字参数,kw接收的是一个dict字典
Python使用map将首字母大写
1 # coding:utf-8 2 name = ['admIn', 'asdOJojnqg12', 'usEr'] 3 4 5 def cF(s): 6 b = '' 7 if isinstance(s, str): 8 for a in range(len(s)): 9 if a == 0: 10 b = b + s[0].upper() 11 else: 12 b = b + s[a].lower() 13 return b 14 else: 15 return 'please input a string!' 16 17 18 l = map(cF, name) 19 print l
Python内建的 filter() 函数用于过滤序列:删除序列中指定元素,通过传入的值为true或false判断
如:使用filter过滤1到100的质数
1 def isPrime(n): 2 if n <= 1: 3 return True 4 i = 2 5 while i*i <= n: 6 if n % i == 0: 7 return True 8 i += 1 9 return False 10 11 12 l = [] 13 for i in range(100): 14 l.append(i) 15 print filter(isPrime, l)
functools.partial 的作用就是,把一个函数的某些参数给固定住(也就是设置默认值),返回一个新的函数,调用这个新函数会更简单
#抓取文件
#!/usr/bin/env python import os, shutil, time cwd = os.getcwd() path = '/opt/datasve' src = '/opt/ePMS710_data' if os.path.exists(path): pass else: os.makedirs(path) os.chdir(src) while True: try: for a in os.listdir(src): # print a shutil.copy(a, path) except IOError: print 'ERROR' continue time.sleep(4)
利用Python实现抓取TXT以及excel文档中的高频词组进行数据分析:
# coding=utf-8 import jieba import xlrd import sys reload(sys) sys.setdefaultencoding('utf-8') class wordCatch(object): def word_frequence(self, filename): if filename.endswith('.txt'): t = '' word = open(filename, 'r') for eachline in word: t += eachline elif filename.endswith('.xlsx') or filename.endswith('.xls'): word = xlrd.open_workbook(filename) table = word.sheets()[1] ncols = table.ncols nrows = table.nrows l = [] for i in range(1, nrows): for j in range(1,ncols): row = table.cell(i, j).value # print row l.append(row) t = ''.join(map(str, l)) else: print '文件格式不支持,请联系作者!' nt = '' for s in t: if not s.isalpha(): nt += s from collections import Counter words = [word for word in jieba.cut(nt, cut_all=True) if len(word) > 2 ] c = Counter(words) for word_freq in c.most_common(100): word, freq = word_freq print word, '出现', freq, '次' a = wordCatch() b='C:\Users\Administrator\Desktop\Ab.xlsx' a.word_frequence(b)
Python if 语句:
Python程序语言指定任何非0和非空(null)值为true,0 或者 null为false
如果if条件为一个对象时,系统会自动将其转为对应的boolean类型
Python修改字典内对应键值类型:
#传入字典中的长整型修改为字符串 for i in range(len(value.keys())): bigintvalue = ['updateTime', 'startTime', 'endTime', 'createTime', 'findTime', 'defectId'] if value.keys()[i] in bigintvalue: value[value.keys()[i]] = str(value[value.keys()[i]]) print value.items()[i]
Python获取当前用户桌面路径
import os print os.path.join(os.path.expanduser("~"), "Desktop")
Python两个文件不能交叉引用