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')
相关文章推荐
- Show me the code之Python练习册 Q1~3 优惠券
- python中if __name__ == '__main__': 的解析
- python读txt文件的编码问题
- python基本数据类型-数字
- 开始写blog记录下学习python的过程
- How is map() implemented internally in Python?
- Python语言进行机器学习的开源项目
- 随机验证码生成(python实现)
- python利用wmi修改IP、DNS
- Python爬虫爬验证码实现功能详解
- 十个python程序小技巧
- python 爬虫试手 requests+BeautifulSoup
- python函数
- Python中os及os.path的相关方法
- Python命令Tab自动补全脚本
- Python学习路程day11
- Python简介
- python分析mysql-binlog,统计时间段内各表的操作次数_2016041302
- 几个Python中的基础算法
- 利用Python进行数据分析笔记(一