您的位置:首页 > 编程语言 > Python开发

Show me the code之Python练习册 Q4~7

2016-04-14 09:12 666 查看
"""
问题:任一个英文的纯文本文件,统计其中的单词出现的个数。
"""

import  re

def count(path):
f = open(path, 'r')
s = f.read()
wcount = re.findall('[\S\w+\b]+', s)
print(len(wcount))

if __name__ == '__main__':
count('d:\\test.txt')


"""
问题:你有一个目录,装了很多照片,把它们的尺寸变成都不大于 iPhone5 分辨率的大小。
常用库:图像处理的库:PIL
文件路径查找:glob
"""
from PIL import Image
import glob

width = 100
height = 100

def resize(path):
for png in glob.glob1(path, '*.png'):
fillName= path + png
# 新路径
index = fillName.rfind('.')
targetpath = fillName[:index] + '_resize' + fillName[index:]
img = Image.open(fillName)
# 获取图片尺寸
x, y = img.size
newimg = img.resize((width, height))
newimg.save(targetpath)

if __name__ == '__main__':
resize('f://image/')


"""
问题:你有一个目录,放了你一个月的日记,都是 txt,为了避免分词的问题,假设内容都是英文,请统计出你认为每篇日记最重要的词。
常用库:Counter 列表的统计词频
"""

import re
from collections import Counter

def count(path):
f = open(path, 'r')
s = f.read()
wcount = re.findall('[\S\w+\b]+', s)
print(Counter(wcount).most_common(2))

if __name__ == '__main__':
count('d:\\test.txt')


"""
问题:有个目录,里面是你自己写过的程序,统计一下你写过多少行代码。包括空行和注释,但是要分别列出来。
"""
import re

# 行数
def getLinesCount(path):
count = 0
f = open(path, 'rb')
while True:
buffer = f.read(1024)
if not buffer:
break
count += buffer.count('\r\n'.encode('utf-8'))
f.close()
print(count)
return count

# 正则计算行数
def getLineCount(path):
annotation = r'\s*[#]\w*'
space = r'^\s+$'

code, blank, note = 0, 0, 0
f = open(path, 'rb')
line = f.readline()
line = line.decode('utf-8')

while line:
if re.match(space, line):
blank += 1
code += 1
elif re.match(annotation, line):
note += 1
code += 1
print(line)
else:
code += 1

line = f.readline().decode('utf-8')

print("共有%d行, 其中包含空行 %d行, 注释 %d行。" % (code, blank, note))

if __name__ == '__main__':
getLineCount('d://A02.py')
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: