2014-04-23
1.python优势
通用性程序设计语言;解释性语言;面向对象语言
2.常用字符
()用于函数
#单行注释
''' '''多行注释
" "用于字符串
3.示例
#!/usr/bin/env python
r=eval(input("input a value for r:")) --eval字符转化数字
area= r * r * 3.14159
print "r=",r,"area=",area ---print 后面内容可用括号
验证
shell>python test.py
input a value for r:'7'
r= 7 area= 153.93791
4.标识符
1)字母,数字,下划线组成
2)字母或下划线开头
3)不能为系统关键字
4)可以为任意长度
5.用法
1)变量在使用前必须初始化
2) a,b=b,a ---交换变量
3)int 浮点型转化为整形
4)pow(a,b):a的b次幂
5)strip()去掉空白字符串
c=" ha "
print(c.strip())
ha
//
s = "welcome to python"
print(s.isalnum()) ---判断所有字符是否都为数字或字母
print(s.islower()) ---判断所有存在的字母是否都为小写,忽略其他字符
print(s.isupper()) ---判断所有存在的字母是否都为大写,忽略其他字符
print(s.isspace()) ---判断所有字符是否都为空白字符\n,\t,\r,' '
print("Welcome".isalpha()) ---全为字母
print("2012".isdigit()) ---全为数字
print("first number".isidentifier())
print(s.endswith("thon")) ---以...结尾
print(s.startswith("good")) ---以...开始
print(s.find("come")) --从左边查找
print(s.find("become"))
s1 = s.capitalize() ---首字母大写
print(s1)
s2 = s.title() ---每个单词字母大写
print(s2)
s = "New England"
s3 = s.lower() --把所有字母转化为小写
print(s3)
s4 = s.upper()
print(s4)
s5 = s.swapcase() -- 把大写字母转化为小写,小写转化为大写
print(s5)
s6 = s.replace("England", "Haven") --替换
print(s6)
print(s)
print(s.rfind("o")) ---从右边查找第一个符合的字母,并返回下标
print(s.count("o")) --统计o
s = " Welcome to Python\t"
s1 = s.lstrip() --去掉左边空白字符
print(s1)
s2 = s.rstrip()
print(s2)
s3 = s.strip()
print(s3)
s = "Welcome"
s1 = s.center(11) --在字符串两边补空格,使字符达到指定长度
print(s1)
s2 = s.ljust(11) --在字符左边补空格
print(s2)
s3 = s.rjust(11)
print(s3)
6.数据元素
元组()
list,字典[]
set{}
读取大文件:for line in infile:
7.示例
import os.path
import sys
def main():
f1 = input("enter a source file: ").strip()
f2 = input("enter a target file: ").strip()
if os.path.isfile(f2):
print(f2 + " already exist")
sys.exit()
infile = open(f1, "r")
infile = open(f2, "w")
#copy from input file to output file
countlines = countchars=0
for line in infile:
countlines += 1
countchars += len(line)
outfile.write(line)
print(countlines,"lines and",countchars,"chars copied")
infile.close()
outfile.close()
main()
8.作业
1.统计目录下不同文件的行数
##解析:
1)获取目录(包括子目录)下某类文件的行数;
2)可以自定义需要统计的文件类型;
3)可以捕获非法参数;
4)封装,可以当模块使用。
##操作
>>>import os; ---导入os模块
>>>dir(os) --- 列出os模块中所有的可用方法与属性
>>> dir(os.path)
>>>help(os.path.split)
>>> help(os.walk)
======================================================
Example:
import os
from os.path import join, getsize
for root, dirs, files in os.walk('python/Lib/email'):
print root, "consumes",
print sum([getsize(join(root, name)) for name in files]),
print "bytes in", len(files), "non-directory files"
if 'CVS' in dirs:
dirs.remove('CVS') # don't visit CVS directories
=========================================================
##walk用法示例:
1)-----------显示指定目录下的所有--------
>>>p = os.walk('/home/haha/python/')
>>>for f in p:
print f
('/home/haha/python/', [], ['test.py', 'copy.py', 'random_test.py', 'test.txt', 'rowcount.py'])
2)------------只显示文件-----------------------
>>>for root, dirs, files in os.walk('/home/haha/python'):
print files
['test.py', 'copy.py', 'random_test.py', 'test.txt', 'rowcount.py']
3)------------输出文件放进list-----------------
>>> all_files = []
>>> for root, dirs, files in os.walk('/home/haha/python'):
all_files.extend(files)
>>>all_files
Out[8]: ['test.py', 'copy.py', 'random_test.py', 'test.txt', 'rowcount.py']
4)----------添加目录--------
>>>all_files = []
>>>for root, dirs, files in os.walk('/home/haha/python'):
for f in files:
all_files.append(root + '/' + f) ---root为目录名
Out[11]:
['/home/haha/python/test.py',
'/home/haha/python/copy.py',
'/home/haha/python/random_test.py',
'/home/haha/python/test.txt',
'/home/haha/python/rowcount.py']
5)-------打开文件并统计行数--------
>>>line_num = 0 --初始化行数
>>>for f in all_files:
line_num += len(open(f).readlines())
>>>line_num
Out[15]: 59
6)----组合--------
>>>all_files = []
>>>for root, dirs, files in os.walk('/home/haha/python'):
for f in files:
all_files.append(root + '/' + f) ---root为目录名
>>>line_num = 0
>>>for f in all_files:
line_num += len(open(f).readlines())
>>>line_num
7)方案
#!/usr/bin/env python
import os
from collections import defaultdict
d = defaultdict(int)
for dirpath, dirnames, filenames in os.walk( '/home/haha/'):
for filename in filenames:
path = os.path.join(dirpath, filename)
ext = os.path.splitext(filename)[1]
d[ext] += len(list(open(path)))
for ext, n_lines in d.items():
print ext, n_lines
==============================================================
方案二:
import os.path
aa = {'xml': 0, 'clj': 0, "other": 0, 'java':0}
def computeLineCnt(filePath):
try:
f = open(filePath, 'r')
cnt = 0
for line in f:
cnt += 1
print filePath + " = " + str(cnt)
return cnt
except:
return 0
def visit(arg, dirname, names):
for item in names:
path = os.path.join(dirname, item)
if os.path.isfile(path):
if len(item.split(".")) > 1:
ext = item.split(".")
if ext == "xml":
aa['xml'] += computeLineCnt(path)
elif ext == "clj":
aa['clj'] += computeLineCnt(path)
elif ext == "java":
aa['java'] += computeLineCnt(path)
else:
# aa['other'] += computeLineCnt(path)
print "-----"
os.path.walk("/home/ivan", visit, None)
===================================================
2.判断系统产生的随机数(1-10)
#!/usr/bin/env python
import random
r = random.randint(1,10)
n = 0
c = 0
while n != r and c < 3:
n = input("please enter n: ")
if n < r:
print "no,it is higher than that\n"
elif n > r:
print "no,it is lower than that\n"
c = c + 1
if n == r:
print "congratulations\n"
else:
print "good luck next time\n"
print "the right number is",r
错误:
调用模块时出现AttributeError: 'module' object has no attribute 'randint'
原因分析:You have anther file named "random.py" on the Python path that is read before the random module is reached.
解决方法:重命名该文件,不能使用系统关键字命名。