diff --git a/.gitignore b/.gitignore index cf1f711b..85dbb806 100644 --- a/.gitignore +++ b/.gitignore @@ -55,3 +55,4 @@ target/ # Mac File .DS_Store +.idea diff --git a/.gitmodules b/.gitmodules new file mode 100644 index 00000000..7b71afcc --- /dev/null +++ b/.gitmodules @@ -0,0 +1,3 @@ +[submodule "JiYouMCC"] + path = JiYouMCC + url = https://github.com/JiYouMCC/python-show-me-the-code diff --git a/4disland/0000/add_num.py b/4disland/0000/add_num.py new file mode 100644 index 00000000..918732f8 --- /dev/null +++ b/4disland/0000/add_num.py @@ -0,0 +1,14 @@ +from PIL import Image, ImageDraw, ImageFont + +def add_num(img): + draw = ImageDraw.Draw(img) + myfont = ImageFont.truetype('C:/windows/fonts/Arial.ttf', size=40) + fillcolor = "#ff0000" + width, height = img.size + draw.text((width-40, 0), '99', font=myfont, fill=fillcolor) + img.save('result.jpg','jpeg') + + return 0 +if __name__ == '__main__': + image = Image.open('image.jpg') + add_num(image) \ No newline at end of file diff --git a/AK-wang/0001/key_gen.py b/AK-wang/0001/key_gen.py new file mode 100755 index 00000000..894ca0d9 --- /dev/null +++ b/AK-wang/0001/key_gen.py @@ -0,0 +1,37 @@ +#!/usr/bin/env python +# -*-coding:utf-8-*- + +# 第 0001 题:做为 Apple Store App 独立开发者,你要搞限时促销,为你的应用生成激活码(或者优惠券), +# 使用 Python 如何生成 200 个激活码(或者优惠券)? + +import string +import random + +KEY_LEN = 20 +KEY_ALL = 200 + + +def base_str(): + return (string.letters + string.digits) + + +def key_gen(): + keylist = [random.choice(base_str()) for i in range(KEY_LEN)] + return ("".join(keylist)) + + +def key_num(num, result=None): + if result is None: + result = [] + for i in range(num): + result.append(key_gen()) + return result + + +def print_key(num): + for i in key_num(num): + print i + + +if __name__ == "__main__": + print_key(KEY_ALL) diff --git a/AK-wang/0001/key_gen_deco.py b/AK-wang/0001/key_gen_deco.py new file mode 100755 index 00000000..e6706969 --- /dev/null +++ b/AK-wang/0001/key_gen_deco.py @@ -0,0 +1,41 @@ +#!/usr/bin/env python +# -*-coding:utf-8-*- + +# 第 0001 题:做为 Apple Store App 独立开发者,你要搞限时促销,为你的应用生成激活码(或者优惠券), +# 使用 Python 如何生成 200 个激活码(或者优惠券)? + +import string +import random + +KEY_LEN = 20 +KEY_ALL = 200 + + +def base_str(): + return (string.letters+string.digits) + + +def key_gen(): + keylist = [random.choice(base_str()) for i in range(KEY_LEN)] + return ("".join(keylist)) + + +def print_key(func): + def _print_key(num): + for i in func(num): + print i + return _print_key + + +@print_key +def key_num(num, result=None): + if result is None: + result = [] + for i in range(num): + result.append(key_gen()) + return result + + +if __name__ == "__main__": + # print_key(KEY_ALL) + key_num(KEY_ALL) diff --git a/AK-wang/0002/save_key.py b/AK-wang/0002/save_key.py new file mode 100755 index 00000000..1347d53e --- /dev/null +++ b/AK-wang/0002/save_key.py @@ -0,0 +1,131 @@ +#!/usr/bin/env python +# -*-coding:utf-8-*- + +# 第 0002 题:将 0001 题生成的 200 个激活码(或者优惠券)保存到 MySQL 关系型数据库中。 + +import MySQLdb +import string +import random + +KEY_LEN = 20 +KEY_ALL = 200 + + +def base_str(): + return (string.letters + string.digits) + + +def key_gen(): + keylist = [random.choice(base_str()) for i in range(KEY_LEN)] + return ("".join(keylist)) + + +def key_num(num, result=None): + if result is None: + result = [] + for i in range(num): + result.append(str(key_gen())) + return result + + +class mysql_init(object): + + def __init__(self, conn): + self.conn = None + + # connect to mysql + def connect(self): + self.conn = MySQLdb.connect( + host="localhost", + port=3306, + user="root", + passwd="123456", + db="test", + charset="utf8" + ) + + def cursor(self): + try: + return self.conn.cursor() + except (AttributeError, MySQLdb.OperationalError): + self.connect() + return self.conn.cursor() + + def commit(self): + return self.conn.commit() + + def close(self): + return self.conn.close() + + +def process(): + dbconn.connect() + conn = dbconn.cursor() + DropTable(conn) + CreateTable(conn) + InsertDatas(conn) + QueryData(conn) + dbconn.close() + +# def execute(sql): +# '''执行sql''' +# conn=dbconn.cursor() +# conn.execute(sql) + +# def executemany(sql, tmp): +# '''插入多条数据''' +# conn=dbconn.cursor() +# conn.executemany(sql,tmp) + + +def query(sql, conn): + '''查询sql''' + # conn=dbconn.cursor() + conn.execute(sql) + rows = conn.fetchall() + return rows + + +def DropTable(conn): + # conn=dbconn.cursor() + conn.execute("DROP TABLE IF EXISTS `user_key`") + + +def CreateTable(conn): + # conn=dbconn.cursor() + sql_create = ''' CREATE TABLE `user_key` (`key` varchar(50) NOT NULL)''' + conn.execute(sql_create) + + +def InsertDatas(conn): + # conn=dbconn.cursor() + # insert_sql = "insert into user_key values(%s)" + insert_sql = "INSERT INTO user_key VALUES (%(value)s)" + key_list = key_num(KEY_ALL) + # print len(key_list) + # conn.executemany(insert_sql,str(key_listi)) + # conn.executemany("INSERT INTO user_key VALUES (%(value)s)", + # [dict(value=v) for v in key_list]) + conn.executemany(insert_sql, [dict(value=v) for v in key_list]) + + +def DeleteData(): + del_sql = "delete from user_key where id=2" + execute(del_sql) + + +def QueryData(conn): + sql = "select * from user_key" + rows = query(sql, conn) + printResult(rows) + + +def printResult(rows): + if rows is None: + print "rows None" + for row in rows: + print row + +if __name__ == "__main__": + dbconn = mysql_init(None) + process() diff --git a/AK-wang/0003/save_to_redis.py b/AK-wang/0003/save_to_redis.py new file mode 100755 index 00000000..936bef59 --- /dev/null +++ b/AK-wang/0003/save_to_redis.py @@ -0,0 +1,48 @@ +#!/usr/bin/env python +# -*-coding:utf-8-*- + +# 第 0003 题:将 0001 题生成的 200 个激活码(或者优惠券)保存到 Redis 非关系型数据库中。 + +import string +import random +import redis + +KEY_LEN = 20 +KEY_ALL = 200 + + +def base_str(): + return (string.letters + string.digits) + + +def key_gen(): + keylist = [random.choice(base_str()) for i in range(KEY_LEN)] + return ("".join(keylist)) + + +def key_num(num, result=None): + if result is None: + result = [] + for i in range(num): + result.append(key_gen()) + return result + + +def redis_init(): + r = redis.Redis(host='localhost', port=6379, db=0) + return r + + +def push_to_redis(key_list): + for key in key_list: + redis_init().lpush('key', key) + + +def get_from_redis(): + key_list = redis_init().lrange('key', 0, -1) + for key in key_list: + print key + +if __name__ == "__main__": + push_to_redis(key_num(200)) + get_from_redis() diff --git a/AK-wang/0004/0004.py b/AK-wang/0004/0004.py new file mode 100755 index 00000000..819d47ad --- /dev/null +++ b/AK-wang/0004/0004.py @@ -0,0 +1,24 @@ +#!/usr/bin/env python +# -*-coding:utf-8-*- + +# 第 0004 题:任一个英文的纯文本文件,统计其中的单词出现的个数 + +from collections import Counter +import re + + +def creat_list(filename): + datalist = [] + with open(filename, 'r') as f: + for line in f: + content = re.sub("\"|,|\.", "", line) + datalist.extend(content.strip().split(' ')) + return datalist + + +def wc(filename): + print Counter(creat_list(filename)) + +if __name__ == "__main__": + filename = 'test.txt' + wc(filename) diff --git a/AK-wang/0004/test.txt b/AK-wang/0004/test.txt new file mode 100644 index 00000000..ca7280b2 --- /dev/null +++ b/AK-wang/0004/test.txt @@ -0,0 +1,4 @@ +In the latest move to support the economy, +Shanghai, Beijing, Chongqing and six other provinces and municipalities will allow banks to refinance high-quality credit assets rated by the People's Bank of China, + said the central bank, as the program was first introduced in Guangdong and Shandong provinces last year. + diff --git a/AK-wang/0006/00.txt b/AK-wang/0006/00.txt new file mode 100644 index 00000000..cbb60433 --- /dev/null +++ b/AK-wang/0006/00.txt @@ -0,0 +1,5 @@ +In China, when people go across the road, they will never wait for the red light + patiently. In fact, Chinese people are famous for running the green light, it +seems to be a habit for them, the traffic rule is just the paper for them, they + never obey it. The result of going against the traffic rule is serious. +we we we we we we we diff --git a/AK-wang/0006/01.txt b/AK-wang/0006/01.txt new file mode 100644 index 00000000..c28a31c3 --- /dev/null +++ b/AK-wang/0006/01.txt @@ -0,0 +1,8 @@ +On the one hand, running the red light is not a civilized behavior, Chinese +people will bring the foreign people the bad impression. When a foreigner comes + to China, he is so curious about the way Chinese people go across the road, he + waits for the green light, while a lot of Chinese people ignore the traffic +rule and go directly. He feels so hilarious about the situation, it is so +uncivilized behavior. +python python python python python python python python python python python +is the best useful language! diff --git a/AK-wang/0006/02.txt b/AK-wang/0006/02.txt new file mode 100644 index 00000000..0788ad87 --- /dev/null +++ b/AK-wang/0006/02.txt @@ -0,0 +1,4 @@ +On the other hand, running the red light results in accident, people will lose +their lives. Every year, many people die of car accident, the main reason is +that they do not obey the traffic rule, when they go across the road, the car +hits them and the tragedy happens. diff --git a/AK-wang/0006/key_word.py b/AK-wang/0006/key_word.py new file mode 100755 index 00000000..cf151bc0 --- /dev/null +++ b/AK-wang/0006/key_word.py @@ -0,0 +1,32 @@ +#!/usr/bin/env python +# -*-coding:utf-8-*- + +# 第 0006 题:你有一个目录,放了你一个月的日记,都是 txt,为了避免分词的问题,假设内容都是英文,请统计出你认为每篇日记最重要的词。 + +import glob +from collections import Counter +import re + + +def list_txt(): + return glob.glob("*.txt") + + +def wc(filename): + datalist = [] + with open(filename, 'r') as f: + for line in f: + content = re.sub("\"|,|\.", "", line) + datalist.extend(content.strip().split(' ')) + # print datalist + return Counter(datalist).most_common(1) + + +def most_comm(): + all_txt = list_txt() + for txt in all_txt: + print wc(txt) + +if __name__ == "__main__": + # most_comm() + print map(wc, list_txt()) diff --git a/AK-wang/0011/filtered_words.py b/AK-wang/0011/filtered_words.py new file mode 100755 index 00000000..88f70ffb --- /dev/null +++ b/AK-wang/0011/filtered_words.py @@ -0,0 +1,30 @@ +#!/usr/bin/env python +# -*-coding:utf-8-*- + +# 第 0011 题: 敏感词文本文件 filtered_words.txt,里面的内容为以下内容, +# 当用户输入敏感词语时,则打印出 Freedom,否则打印出 Human Rights。 + + +def filtered_words(f_file): + filtered_list = [] + with open(f_file, 'r') as f: + for line in f: + filtered_list.append(line.strip()) + return filtered_list + + +def filtered_or_not(input_word, f_file): + filtered_words_list = filtered_words(f_file) + return (input_word in filtered_words_list) + + +def print_user_input(input_word, f_file): + if filtered_or_not(input_word, f_file): + return "Freedom" + return "Human Rights" + + +if __name__ == "__main__": + input_word = raw_input("please input your word:") + f_file = "filtered_words.txt" + print print_user_input(input_word, f_file) diff --git a/AK-wang/0011/filtered_words.txt b/AK-wang/0011/filtered_words.txt new file mode 100644 index 00000000..1b4f2244 --- /dev/null +++ b/AK-wang/0011/filtered_words.txt @@ -0,0 +1,11 @@ +北京 +程序员 +公务员 +领导 +牛比 +牛逼 +你娘 +你妈 +love +sex +jiangge diff --git a/AK-wang/0012/f_replace.py b/AK-wang/0012/f_replace.py new file mode 100755 index 00000000..bf94a1e6 --- /dev/null +++ b/AK-wang/0012/f_replace.py @@ -0,0 +1,35 @@ +#!/usr/bin/env python +# -*-coding:utf-8-*- + +# 第 0012 题: 敏感词文本文件 filtered_words.txt,里面的内容 和 0011题一样,当用户输入敏感词语,则用 星号 * 替换, +# 例如当用户输入「北京是个好城市」,则变成「**是个好城市」。 + + +def f_words(f_file): + filtered_list = [] + with open(f_file, 'r') as f: + for line in f: + filtered_list.append(line.strip()) + return filtered_list + + +def filtered_or_not(f_word, input_str): + return (f_word in input_str) + + +def f_replace(f_word, input_str): + return input_str.replace(f_word, "**") + + +def main(f_file, input_str): + f_words_list = f_words(f_file) + for f_word in f_words_list: + if filtered_or_not(f_word, input_str): + input_str = f_replace(f_word, input_str) + return input_str + + +if __name__ == "__main__": + input_str = raw_input("please input your string:") + f_file = "filtered_words.txt" + print main(f_file, input_str) diff --git a/AK-wang/0012/filtered_words.txt b/AK-wang/0012/filtered_words.txt new file mode 100644 index 00000000..1b4f2244 --- /dev/null +++ b/AK-wang/0012/filtered_words.txt @@ -0,0 +1,11 @@ +北京 +程序员 +公务员 +领导 +牛比 +牛逼 +你娘 +你妈 +love +sex +jiangge diff --git a/AK-wang/A0000/sushu.py b/AK-wang/A0000/sushu.py new file mode 100755 index 00000000..63376d47 --- /dev/null +++ b/AK-wang/A0000/sushu.py @@ -0,0 +1,30 @@ +#!/bin/env python +#-*-coding:utf-8-*- +#寻找n以内的素数,看执行时间,例子100000内的素数 +import sys + +def prime(n): + flag = [1]*(n+2) + flag[1] = 0 # 1 is not prime + flag[n+1] = 1 + p=2 + while(p<=n): + print p + for i in xrange(2*p,n+1,p): + flag[i] = 0 + while 1: + p += 1 + if(flag[p]==1): + break +# test +if __name__ == "__main__": + n = int(sys.argv[1]) + prime(n) + +# n = 100000,find 9592 primes +#$ time ./sushu.py 100000 |wc -l +#9592 + +#real 0m0.083s +#user 0m0.078s +#sys 0m0.009s diff --git a/AK-wang/A0000/sushu_v0.1.py b/AK-wang/A0000/sushu_v0.1.py new file mode 100755 index 00000000..98cd7532 --- /dev/null +++ b/AK-wang/A0000/sushu_v0.1.py @@ -0,0 +1,30 @@ +#!/bin/env python +#-*-coding:utf-8-*- + +import sys +import math + +def prime(n): + if n%2 == 0: + return n==2 + if n%3 == 0: + return n==3 + if n%5 == 0: + return n==5 + for p in xrange(7,int(math.sqrt(n))+1,2): #只考虑奇数作为可能因子 + if n%p == 0: + return 0 + return 1 + +if __name__ == "__main__": + n = int(sys.argv[1]) + for i in xrange(2,n+1): #1不是素数,从2开始 + if prime(i): + print i + +#$ time ./sushu_v0.1.py 100000|wc -l +#9592 + +#real 0m0.287s +#user 0m0.282s +#sys 0m0.009s diff --git a/AK-wang/A0001/floor_step.C b/AK-wang/A0001/floor_step.C new file mode 100644 index 00000000..ffa0bd54 --- /dev/null +++ b/AK-wang/A0001/floor_step.C @@ -0,0 +1,102 @@ +/* + +下楼问题。从楼上走到楼下共有h个台阶,每一步有三种走法: +走1个台阶,走2个台阶,走3个台阶。问有多少可走的方案。用递归思想和迭代思想编程。 + +*/ + +#include +#include +#include + +static int stack[1024]; // 存放每一步的台阶数 +static int steps = 0; // 走过的步数 +static int num_of_method = 0; // 多少种走法 +//递归详细版本,列出每一种走法的步骤 +void NextStairs(int n) +{ + if(n == 0) + { + /* 走完所有台阶,打印本次的走法,即曾经走过的步骤 */ + printf("第%3d种走法[需%3d步] : ", ++num_of_method, steps); + int i; + for(i=0; i= 1) + { + stack[steps++] = 1; // 本次走1个台阶 + NextStairs(n-1); + steps --; + } + if(n >= 2) + { + stack[steps++] = 2; // 本次走2个台阶 + NextStairs(n-2); + steps --; + } + if(n >= 3) + { + stack[steps++] = 3; // 本次走3个台阶 + NextStairs(n-3); + steps --; + } +} +//迭代法 +//此处是归纳出下一次z的迭代规律,下一次的z的值是上一次x,y,z的和,然后每次都要更新x,y,z +int fib3(int n) +{ + + int x = 0, y = 0,z=1; + int w, k; + + for (int j = 0; j < n; j++) + { + + w = z; + k = y; + z = x + y + z; + y = w; + x = k; + + + } + + return z; + +} +//递归法 +int dfib1(int n) +{ + if (n < 1) + { return 0; } + + if (n == 1) + return 1; + if (n == 2) + return 2; + if (n == 3) + return 4; + return dfib1(n - 1) + dfib1(n - 2) + dfib1(n-3); +} + +int main() +{ + int n; + printf("enter a positive number: n="); + scanf("%d", &n); + + //NextStairs(n); + //printf("%d\n", dfib1(n)); + printf("%d\n", fib3(n)); + + return 0; +} + + + + diff --git a/AK-wang/README.md b/AK-wang/README.md new file mode 100644 index 00000000..4b2c0823 --- /dev/null +++ b/AK-wang/README.md @@ -0,0 +1,199 @@ +## Python 练习册,每天一个小程序 ## + + +#### 说明: #### + +- Python 练习册,每天一个小程序。注:将 Python 换成其他语言,大多数题目也适用 +- 不会出现诸如「打印九九乘法表」、「打印水仙花」之类的题目 +- [点此链接,会看到每个题目的代码, 欢迎大家 Pull Request 出题目,贴代码(Gist、Blog皆可),Pull Request 请提交你个人的仓库 URL 链接地址。现在项目太大了,提交 URL 吧 :+1: :-)](https://github.com/Show-Me-the-Code/python) +- 本文本文由@史江歌(shijiangge@gmail.com QQ:499065469)根据互联网资料收集整理而成,感谢互联网,感谢各位的分享。鸣谢!本文会不断更新。 + +> Talk is cheap. Show me the code.--Linus Torvalds + +---------- + +**第 0000 题:**将你的 QQ 头像(或者微博头像)右上角加上红色的数字,类似于微信未读信息数量那种提示效果。 +类似于图中效果 + +![头像](http://i.imgur.com/sg2dkuY.png?1) + +**第 0001 题:**做为 Apple Store App 独立开发者,你要搞限时促销,为你的应用**生成激活码**(或者优惠券),使用 Python 如何生成 200 个激活码(或者优惠券)? + +**第 0002 题**:将 0001 题生成的 200 个激活码(或者优惠券)保存到 **MySQL** 关系型数据库中。 + +**第 0003 题:**将 0001 题生成的 200 个激活码(或者优惠券)保存到 **Redis** 非关系型数据库中。 + +**第 0004 题:**任一个英文的纯文本文件,统计其中的单词出现的个数。 + +**第 0005 题:**你有一个目录,装了很多照片,把它们的尺寸变成都不大于 iPhone5 分辨率的大小。 + +**第 0006 题:**你有一个目录,放了你一个月的日记,都是 txt,为了避免分词的问题,假设内容都是英文,请统计出你认为每篇日记最重要的词。 + +**第 0007 题:**有个目录,里面是你自己写过的程序,统计一下你写过多少行代码。包括空行和注释,但是要分别列出来。 + +**第 0008 题:**一个HTML文件,找出里面的**正文**。 + +**第 0009 题:**一个HTML文件,找出里面的**链接**。 + +**第 0010 题:**使用 Python 生成类似于下图中的**字母验证码图片** + +![字母验证码](http://i.imgur.com/aVhbegV.jpg) + +- [阅读资料](http://stackoverflow.com/questions/2823316/generate-a-random-letter-in-python) + +**第 0011 题:** 敏感词文本文件 filtered_words.txt,里面的内容为以下内容,当用户输入敏感词语时,则打印出 Freedom,否则打印出 Human Rights。 + + 北京 + 程序员 + 公务员 + 领导 + 牛比 + 牛逼 + 你娘 + 你妈 + love + sex + jiangge + +**第 0012 题:** 敏感词文本文件 filtered_words.txt,里面的内容 和 0011题一样,当用户输入敏感词语,则用 星号 * 替换,例如当用户输入「北京是个好城市」,则变成「**是个好城市」。 + +**第 0013 题:** 用 Python 写一个爬图片的程序,爬 [这个链接里的日本妹子图片 :-)](http://tieba.baidu.com/p/2166231880) + +- [参考代码](http://www.v2ex.com/t/61686 "参考代码") + +**第 0014 题:** 纯文本文件 student.txt为学生信息, 里面的内容(包括花括号)如下所示: + + { + "1":["张三",150,120,100], + "2":["李四",90,99,95], + "3":["王五",60,66,68] + } + +请将上述内容写到 student.xls 文件中,如下图所示: + +![student.xls](http://i.imgur.com/nPDlpme.jpg) + +- [阅读资料](http://www.cnblogs.com/skynet/archive/2013/05/06/3063245.html) 腾讯游戏开发 XML 和 Excel 内容相互转换 + +**第 0015 题:** 纯文本文件 city.txt为城市信息, 里面的内容(包括花括号)如下所示: + + { + "1" : "上海", + "2" : "北京", + "3" : "成都" + } + +请将上述内容写到 city.xls 文件中,如下图所示: + +![city.xls](http://i.imgur.com/rOHbUzg.png) + + +**第 0016 题:** 纯文本文件 numbers.txt, 里面的内容(包括方括号)如下所示: + + [ + [1, 82, 65535], + [20, 90, 13], + [26, 809, 1024] + ] + +请将上述内容写到 numbers.xls 文件中,如下图所示: + +![numbers.xls](http://i.imgur.com/iuz0Pbv.png) + +**第 0017 题:** 将 第 0014 题中的 student.xls 文件中的内容写到 student.xml 文件中,如 + +下所示: + + + + + + { + "1" : ["张三", 150, 120, 100], + "2" : ["李四", 90, 99, 95], + "3" : ["王五", 60, 66, 68] + } + + + + +**第 0018 题:** 将 第 0015 题中的 city.xls 文件中的内容写到 city.xml 文件中,如下所示: + + + + + + { + "1" : "上海", + "2" : "北京", + "3" : "成都" + } + + + +**第 0019 题:** 将 第 0016 题中的 numbers.xls 文件中的内容写到 numbers.xml 文件中,如下 + +所示: + + + + + + + [ + [1, 82, 65535], + [20, 90, 13], + [26, 809, 1024] + ] + + + + +**第 0020 题:** [登陆中国联通网上营业厅](http://iservice.10010.com/index_.html) 后选择「自助服务」 --> 「详单查询」,然后选择你要查询的时间段,点击「查询」按钮,查询结果页面的最下方,点击「导出」,就会生成类似于 2014年10月01日~2014年10月31日通话详单.xls 文件。写代码,对每月通话时间做个统计。 + +**第 0021 题:** 通常,登陆某个网站或者 APP,需要使用用户名和密码。密码是如何加密后存储起来的呢?请使用 Python 对密码加密。 + +- 阅读资料 [用户密码的存储与 Python 示例](http://zhuoqiang.me/password-storage-and-python-example.html) + +- 阅读资料 [Hashing Strings with Python](http://www.pythoncentral.io/hashing-strings-with-python/) + +- 阅读资料 [Python's safest method to store and retrieve passwords from a database](http://stackoverflow.com/questions/2572099/pythons-safest-method-to-store-and-retrieve-passwords-from-a-database) + +**第 0022 题:** iPhone 6、iPhone 6 Plus 早已上市开卖。请查看你写得 第 0005 题的代码是否可以复用。 + +**第 0023 题:** 使用 Python 的 Web 框架,做一个 Web 版本 留言簿 应用。 + +[阅读资料:Python 有哪些 Web 框架](http://v2ex.com/t/151643#reply53) + +- ![留言簿参考](http://i.imgur.com/VIyCZ0i.jpg) + + +**第 0024 题:** 使用 Python 的 Web 框架,做一个 Web 版本 TodoList 应用。 + +- ![SpringSide 版TodoList](http://i.imgur.com/NEf7zHp.jpg) + +**第 0025 题:** 使用 Python 实现:对着电脑吼一声,自动打开浏览器中的默认网站。 + + + 例如,对着笔记本电脑吼一声“百度”,浏览器自动打开百度首页。 + + 关键字:Speech to Text + +参考思路: +1:获取电脑录音-->WAV文件 + python record wav + +2:录音文件-->文本 + + STT: Speech to Text + + STT API Google API + +3:文本-->电脑命令 diff --git a/DIYgod/0000/Futura.ttf b/DIYgod/0000/Futura.ttf new file mode 100644 index 00000000..ddedd04e Binary files /dev/null and b/DIYgod/0000/Futura.ttf differ diff --git a/DIYgod/0000/add_num.py b/DIYgod/0000/add_num.py new file mode 100644 index 00000000..f0954dd9 --- /dev/null +++ b/DIYgod/0000/add_num.py @@ -0,0 +1,14 @@ +# -*- coding:utf-8 -*- +# 第 0000 题:将你的 QQ 头像(或者微博头像)右上角加上红色的数字,类似于微信未读信息数量那种提示效果 + +from PIL import Image, ImageDraw, ImageFont + +def add_num(picPath, num): + img = Image.open(picPath) + x, y = img.size + myfont = ImageFont.truetype('Futura.ttf', x / 3) + ImageDraw.Draw(img).text((2 * x / 3, 0), str(num), font = myfont, fill = 'red') + img.save('pic_with_num.jpg') + +if __name__ == '__main__': + add_num('pic.jpg', 9) diff --git a/DIYgod/0001/Activation_code.txt b/DIYgod/0001/Activation_code.txt new file mode 100644 index 00000000..2174d5e9 --- /dev/null +++ b/DIYgod/0001/Activation_code.txt @@ -0,0 +1,200 @@ +xsdPh4f +8qoW07j +Tnj1HmB +zIT8qAB +FnDnNi0 +3QpZj1O +KlkwRfE +wsdy8NQ +pvXSdlY +pp9LWSn +dS6zQnC +WbCHjJH +jAjJtli +38ykU8k +wMNCQ1m +X245rLW +UWizZgo +YkLduIF +v1GJSdz +BNMZuX5 +yIjRDQu +GNvXIIF +DbWEtTD +F1W2jtg +54bWrUb +b2IEbzZ +xcaOsuG +uXOhegJ +TvKkKSN +KgSCoEJ +elrc80r +DOXohsE +KjdnEGw +ffqwUwX +xdRhBkT +ruceTaI +RZZTs0h +K5EKaNj +VqW5vfD +ownScnm +7rGnRPw +TiaUfFy +7YSMWr0 +C9YkCdo +6ikBwSy +qiETLg6 +aKDPWxE +b3cCXhY +MKA2OKu +9EdcKmD +0qeKaui +ejpFFlC +SmC9Nor +mCPyWEv +kStIHKd +9DkalxT +jWColwT +GcTkSXk +V5UrDSg +ekrLbCf +cQXARzF +UP7ksMd +MGVEVVH +tKlLsKA +bz978B2 +3d6BchN +FQaaOIJ +CVOzpVy +5S41CmW +BrEcQpZ +RgpvtTu +eNIFEtp +IYA1GXy +aVofZsk +RtR05Dr +RtKSB4v +ylWhH4I +E1rTSQQ +km1GyrM +1YhC46I +Yth5Mop +h1rq8Zt +1N33N7j +k5BXCmg +E1wPDwt +uvWFfTk +QaExb9R +xmbbV3I +Jiqxv4q +t86xdCq +hjnITkf +X7QfU9R +BNrvD6R +TrD8RKS +j4Hb5m0 +Ej01pN1 +DjBieTP +TF1Yhw3 +P8Hvl0h +iuQIBSZ +7hYH1nu +Keddid3 +UMhZAlX +yEBxCNV +h9eUhig +Uf2FGRg +D6mGp0Y +slkzCJF +d2MtwFg +H4P7dA5 +dh3uvgk +hV67DzW +kS6veXF +QWs0IBe +mUTAsKo +bA3ZmDA +bdzo5aa +ssP0Ioy +bSzxPwX +Yvx2TwW +B8RHjhI +f1k9PHy +JT6UjuI +UrUzUMT +gatlmvG +Z0IcjOW +WSeJD71 +xn2TEqq +l6XMop0 +cebTTJx +JAFSQP7 +hP86mW8 +uTbUfPI +uInfJSv +PkWbVsD +Soc04tS +Trv2Tli +p9OQOR6 +2E63ef8 +mOIm6vn +pvY48CT +18u0DeJ +G65JpBW +fXAyrcL +nujVYv3 +Zmcu79i +NPtWjMc +Xhsc44i +cpVKhfM +QiwFFGB +YbBpW33 +ShzJeoe +rRVzaA2 +9P9TjOA +9DCcFW6 +eV9kso8 +ylNtW8l +cg4NDrW +z9jG8LY +p8DRxic +v60BL2p +7gXCYhl +bRFKTnV +9hAeREO +UF8Ushb +zHnAsxJ +qIEgxWg +B2gMwr8 +fyTx67J +14iRytg +hLludCg +jMVkbU1 +lFQQ1YX +stOGahb +cgB8aJC +eVyrvc7 +eftb4Ge +MFyiWOO +hAf6Hha +b884B8F +qXaVpDs +z1PYqm3 +YXZz3YI +LZgQpdZ +HpYkmdw +uhR1wth +mwfz0kk +9AlVldl +pQ8xzhi +5tPou1g +ahNqlgN +euCV2IH +tg9b7s8 +Z4r2aA6 +JYUijB2 +k6tMe54 +LJuhb7x +Z6VPjwe +U3qgd0G +a9RH5fF diff --git a/DIYgod/0001/random_string.py b/DIYgod/0001/random_string.py new file mode 100644 index 00000000..d43c32e1 --- /dev/null +++ b/DIYgod/0001/random_string.py @@ -0,0 +1,15 @@ +# -*- coding: utf-8 -*- +# 第 0001 题:做为 Apple Store App 独立开发者,你要搞限时促销,为你的应用生成激活码(或者优惠券),使用 Python 如何生成 200 个激活码(或者优惠券)? + +import random, string + +def rand_str(num, length = 7): + f = open('Activation_code.txt', 'wb') + for i in range(num): + chars = string.letters + string.digits + s = [random.choice(chars) for i in range(length)] + f.write(''.join(s) + '\n') + f.close() + +if __name__ == '__main__': + rand_str(200) diff --git a/DIYgod/0002/Activation_code.txt b/DIYgod/0002/Activation_code.txt new file mode 100644 index 00000000..2174d5e9 --- /dev/null +++ b/DIYgod/0002/Activation_code.txt @@ -0,0 +1,200 @@ +xsdPh4f +8qoW07j +Tnj1HmB +zIT8qAB +FnDnNi0 +3QpZj1O +KlkwRfE +wsdy8NQ +pvXSdlY +pp9LWSn +dS6zQnC +WbCHjJH +jAjJtli +38ykU8k +wMNCQ1m +X245rLW +UWizZgo +YkLduIF +v1GJSdz +BNMZuX5 +yIjRDQu +GNvXIIF +DbWEtTD +F1W2jtg +54bWrUb +b2IEbzZ +xcaOsuG +uXOhegJ +TvKkKSN +KgSCoEJ +elrc80r +DOXohsE +KjdnEGw +ffqwUwX +xdRhBkT +ruceTaI +RZZTs0h +K5EKaNj +VqW5vfD +ownScnm +7rGnRPw +TiaUfFy +7YSMWr0 +C9YkCdo +6ikBwSy +qiETLg6 +aKDPWxE +b3cCXhY +MKA2OKu +9EdcKmD +0qeKaui +ejpFFlC +SmC9Nor +mCPyWEv +kStIHKd +9DkalxT +jWColwT +GcTkSXk +V5UrDSg +ekrLbCf +cQXARzF +UP7ksMd +MGVEVVH +tKlLsKA +bz978B2 +3d6BchN +FQaaOIJ +CVOzpVy +5S41CmW +BrEcQpZ +RgpvtTu +eNIFEtp +IYA1GXy +aVofZsk +RtR05Dr +RtKSB4v +ylWhH4I +E1rTSQQ +km1GyrM +1YhC46I +Yth5Mop +h1rq8Zt +1N33N7j +k5BXCmg +E1wPDwt +uvWFfTk +QaExb9R +xmbbV3I +Jiqxv4q +t86xdCq +hjnITkf +X7QfU9R +BNrvD6R +TrD8RKS +j4Hb5m0 +Ej01pN1 +DjBieTP +TF1Yhw3 +P8Hvl0h +iuQIBSZ +7hYH1nu +Keddid3 +UMhZAlX +yEBxCNV +h9eUhig +Uf2FGRg +D6mGp0Y +slkzCJF +d2MtwFg +H4P7dA5 +dh3uvgk +hV67DzW +kS6veXF +QWs0IBe +mUTAsKo +bA3ZmDA +bdzo5aa +ssP0Ioy +bSzxPwX +Yvx2TwW +B8RHjhI +f1k9PHy +JT6UjuI +UrUzUMT +gatlmvG +Z0IcjOW +WSeJD71 +xn2TEqq +l6XMop0 +cebTTJx +JAFSQP7 +hP86mW8 +uTbUfPI +uInfJSv +PkWbVsD +Soc04tS +Trv2Tli +p9OQOR6 +2E63ef8 +mOIm6vn +pvY48CT +18u0DeJ +G65JpBW +fXAyrcL +nujVYv3 +Zmcu79i +NPtWjMc +Xhsc44i +cpVKhfM +QiwFFGB +YbBpW33 +ShzJeoe +rRVzaA2 +9P9TjOA +9DCcFW6 +eV9kso8 +ylNtW8l +cg4NDrW +z9jG8LY +p8DRxic +v60BL2p +7gXCYhl +bRFKTnV +9hAeREO +UF8Ushb +zHnAsxJ +qIEgxWg +B2gMwr8 +fyTx67J +14iRytg +hLludCg +jMVkbU1 +lFQQ1YX +stOGahb +cgB8aJC +eVyrvc7 +eftb4Ge +MFyiWOO +hAf6Hha +b884B8F +qXaVpDs +z1PYqm3 +YXZz3YI +LZgQpdZ +HpYkmdw +uhR1wth +mwfz0kk +9AlVldl +pQ8xzhi +5tPou1g +ahNqlgN +euCV2IH +tg9b7s8 +Z4r2aA6 +JYUijB2 +k6tMe54 +LJuhb7x +Z6VPjwe +U3qgd0G +a9RH5fF diff --git a/DIYgod/0002/store_mysql.py b/DIYgod/0002/store_mysql.py new file mode 100644 index 00000000..e217261c --- /dev/null +++ b/DIYgod/0002/store_mysql.py @@ -0,0 +1,34 @@ +# -*- coding: utf-8 -*- + +import mysql.connector + +def store_mysql(filepath): + conn = mysql.connector.connect(user = 'root', password = '1207', database = 'ShowMeTheCode') + cursor = conn.cursor() + + # 判断表是否已经存在 + cursor.execute('show tables in ShowMeTheCode;') + tables = cursor.fetchall() + findtables = False + for table in tables: + if 'code' in table: + findtables = True + if not findtables: + cursor.execute(''' + CREATE TABLE `ShowMeTheCode`.`code` ( + `id` INT NOT NULL AUTO_INCREMENT, + `code` VARCHAR(10) NOT NULL, + PRIMARY KEY (`id`)); + ''') + + f = open(filepath, 'rb') + for line in f.readlines(): + code = line.strip() + cursor.execute("insert into ShowMeTheCode.code (code) values(%s);", [code]) + + conn.commit() + cursor.close() + conn.close() + +if __name__ == '__main__': + store_mysql('Activation_code.txt') diff --git a/DIYgod/0003/Activation_code.txt b/DIYgod/0003/Activation_code.txt new file mode 100644 index 00000000..2174d5e9 --- /dev/null +++ b/DIYgod/0003/Activation_code.txt @@ -0,0 +1,200 @@ +xsdPh4f +8qoW07j +Tnj1HmB +zIT8qAB +FnDnNi0 +3QpZj1O +KlkwRfE +wsdy8NQ +pvXSdlY +pp9LWSn +dS6zQnC +WbCHjJH +jAjJtli +38ykU8k +wMNCQ1m +X245rLW +UWizZgo +YkLduIF +v1GJSdz +BNMZuX5 +yIjRDQu +GNvXIIF +DbWEtTD +F1W2jtg +54bWrUb +b2IEbzZ +xcaOsuG +uXOhegJ +TvKkKSN +KgSCoEJ +elrc80r +DOXohsE +KjdnEGw +ffqwUwX +xdRhBkT +ruceTaI +RZZTs0h +K5EKaNj +VqW5vfD +ownScnm +7rGnRPw +TiaUfFy +7YSMWr0 +C9YkCdo +6ikBwSy +qiETLg6 +aKDPWxE +b3cCXhY +MKA2OKu +9EdcKmD +0qeKaui +ejpFFlC +SmC9Nor +mCPyWEv +kStIHKd +9DkalxT +jWColwT +GcTkSXk +V5UrDSg +ekrLbCf +cQXARzF +UP7ksMd +MGVEVVH +tKlLsKA +bz978B2 +3d6BchN +FQaaOIJ +CVOzpVy +5S41CmW +BrEcQpZ +RgpvtTu +eNIFEtp +IYA1GXy +aVofZsk +RtR05Dr +RtKSB4v +ylWhH4I +E1rTSQQ +km1GyrM +1YhC46I +Yth5Mop +h1rq8Zt +1N33N7j +k5BXCmg +E1wPDwt +uvWFfTk +QaExb9R +xmbbV3I +Jiqxv4q +t86xdCq +hjnITkf +X7QfU9R +BNrvD6R +TrD8RKS +j4Hb5m0 +Ej01pN1 +DjBieTP +TF1Yhw3 +P8Hvl0h +iuQIBSZ +7hYH1nu +Keddid3 +UMhZAlX +yEBxCNV +h9eUhig +Uf2FGRg +D6mGp0Y +slkzCJF +d2MtwFg +H4P7dA5 +dh3uvgk +hV67DzW +kS6veXF +QWs0IBe +mUTAsKo +bA3ZmDA +bdzo5aa +ssP0Ioy +bSzxPwX +Yvx2TwW +B8RHjhI +f1k9PHy +JT6UjuI +UrUzUMT +gatlmvG +Z0IcjOW +WSeJD71 +xn2TEqq +l6XMop0 +cebTTJx +JAFSQP7 +hP86mW8 +uTbUfPI +uInfJSv +PkWbVsD +Soc04tS +Trv2Tli +p9OQOR6 +2E63ef8 +mOIm6vn +pvY48CT +18u0DeJ +G65JpBW +fXAyrcL +nujVYv3 +Zmcu79i +NPtWjMc +Xhsc44i +cpVKhfM +QiwFFGB +YbBpW33 +ShzJeoe +rRVzaA2 +9P9TjOA +9DCcFW6 +eV9kso8 +ylNtW8l +cg4NDrW +z9jG8LY +p8DRxic +v60BL2p +7gXCYhl +bRFKTnV +9hAeREO +UF8Ushb +zHnAsxJ +qIEgxWg +B2gMwr8 +fyTx67J +14iRytg +hLludCg +jMVkbU1 +lFQQ1YX +stOGahb +cgB8aJC +eVyrvc7 +eftb4Ge +MFyiWOO +hAf6Hha +b884B8F +qXaVpDs +z1PYqm3 +YXZz3YI +LZgQpdZ +HpYkmdw +uhR1wth +mwfz0kk +9AlVldl +pQ8xzhi +5tPou1g +ahNqlgN +euCV2IH +tg9b7s8 +Z4r2aA6 +JYUijB2 +k6tMe54 +LJuhb7x +Z6VPjwe +U3qgd0G +a9RH5fF diff --git a/DIYgod/0003/store_redis.py b/DIYgod/0003/store_redis.py new file mode 100644 index 00000000..d286d380 --- /dev/null +++ b/DIYgod/0003/store_redis.py @@ -0,0 +1,13 @@ +# -*- coding: utf-8 -*- + +import redis + +def store_redis(filepath): + r = redis.StrictRedis(host = 'localhost', port = 6379, db = 0) + f = open(filepath, 'rb') + for line in f.readlines(): + code = line.strip() + r.lpush('code', code) + +if __name__ == '__main__': + store_redis('Activation_code.txt') diff --git a/DIYgod/0004/count_test.txt b/DIYgod/0004/count_test.txt new file mode 100644 index 00000000..b74b9c67 --- /dev/null +++ b/DIYgod/0004/count_test.txt @@ -0,0 +1,3 @@ +Set Up Git + +At the heart of GitHub is an open source version control system (VCS) called Git. Git is responsible for everything GitHub-related that happens locally on your computer. diff --git a/DIYgod/0004/count_word.py b/DIYgod/0004/count_word.py new file mode 100644 index 00000000..a0e9cbf2 --- /dev/null +++ b/DIYgod/0004/count_word.py @@ -0,0 +1,13 @@ +# -*- coding: utf-8 -*- + +import re + +def count(filepath): + f = open(filepath, 'rb') + s = f.read() + words = re.findall(r'[a-zA-Z0-9]+', s) + return len(words) + +if __name__ == '__main__': + num = count('count_test.txt') + print num diff --git a/DIYgod/0005/change_resolution.py b/DIYgod/0005/change_resolution.py new file mode 100644 index 00000000..5ae70b8f --- /dev/null +++ b/DIYgod/0005/change_resolution.py @@ -0,0 +1,20 @@ +# -*- coding: utf-8 -*- + +from PIL import Image + +def change_resolution(picPath, reslution): + img = Image.open(picPath) + x, y = img.size + print x, y + changex = float(x) / reslution[0] + changey = float(y) / reslution[1] + + # 判断分辨率是否满足 + if changex > 1 or changey > 1: + change = changex if changex > changey else changey + print change + print int(reslution[0] / change), int(reslution[1] / change) + img.resize((int(x / change), int(y / change))).save('result.jpg') + +if __name__ == '__main__': + change_resolution('pictest.jpg', (1136, 640)) diff --git a/DIYgod/0006/a.py b/DIYgod/0006/a.py new file mode 100644 index 00000000..85a41a19 --- /dev/null +++ b/DIYgod/0006/a.py @@ -0,0 +1,18 @@ +f = open('a.txt', 'rb') +lines = f.readlines() +for line in lines: + pass +f.close() + +f = open('a.txt', 'rb') +for line in f: + pass +f.close() + +f = open('a.txt', 'rb') +while true: + line = f.readline() + if not line: + break + pass +f.close() diff --git a/DIYgod/0006/important_word.py b/DIYgod/0006/important_word.py new file mode 100644 index 00000000..49b9abce --- /dev/null +++ b/DIYgod/0006/important_word.py @@ -0,0 +1,43 @@ +# -*- coding: utf-8 -*- + +import re +import os + +# Get all files in designated path +def get_files(path): + filepath = os.listdir(path) + files = [] + for fp in filepath: + fppath = path + '/' + fp + if(os.path.isfile(fppath)): + files.append(fppath) + elif(os.path.isdir(fppath)): + files += get_files(fppath) + return files + +# Get the most popular word in designated files +def get_important_word(files): + worddict = {} + for filename in files: + f = open(filename, 'rb') + s = f.read() + words = re.findall(r'[a-zA-Z0-9]+', s) + for word in words: + worddict[word] = worddict[word] + 1 if word in worddict else 1 + f.close() + wordsort = sorted(worddict.items(), key=lambda e:e[1], reverse=True) + return wordsort + +if __name__ == '__main__': + files = get_files('.') + print files + wordsort = get_important_word(files) + # 避免遗漏有多个最大值的情况 + maxnum = 1 + for i in range(len(wordsort) - 1): + if wordsort[i][1] == wordsort[i + 1][1]: + maxnum += 1 + else: + break + for i in range(maxnum): + print wordsort[i] diff --git a/DIYgod/0006/test.py b/DIYgod/0006/test.py new file mode 100644 index 00000000..5ae70b8f --- /dev/null +++ b/DIYgod/0006/test.py @@ -0,0 +1,20 @@ +# -*- coding: utf-8 -*- + +from PIL import Image + +def change_resolution(picPath, reslution): + img = Image.open(picPath) + x, y = img.size + print x, y + changex = float(x) / reslution[0] + changey = float(y) / reslution[1] + + # 判断分辨率是否满足 + if changex > 1 or changey > 1: + change = changex if changex > changey else changey + print change + print int(reslution[0] / change), int(reslution[1] / change) + img.resize((int(x / change), int(y / change))).save('result.jpg') + +if __name__ == '__main__': + change_resolution('pictest.jpg', (1136, 640)) diff --git a/DIYgod/0006/test/test.py b/DIYgod/0006/test/test.py new file mode 100644 index 00000000..5ae70b8f --- /dev/null +++ b/DIYgod/0006/test/test.py @@ -0,0 +1,20 @@ +# -*- coding: utf-8 -*- + +from PIL import Image + +def change_resolution(picPath, reslution): + img = Image.open(picPath) + x, y = img.size + print x, y + changex = float(x) / reslution[0] + changey = float(y) / reslution[1] + + # 判断分辨率是否满足 + if changex > 1 or changey > 1: + change = changex if changex > changey else changey + print change + print int(reslution[0] / change), int(reslution[1] / change) + img.resize((int(x / change), int(y / change))).save('result.jpg') + +if __name__ == '__main__': + change_resolution('pictest.jpg', (1136, 640)) diff --git a/DIYgod/0007/count_lines.py b/DIYgod/0007/count_lines.py new file mode 100644 index 00000000..22a42fbf --- /dev/null +++ b/DIYgod/0007/count_lines.py @@ -0,0 +1,36 @@ +# -*- coding: utf-8 -*- + +import os + +# Get all files in designated path +def get_files(path): + filepath = os.listdir(path) + files = [] + for fp in filepath: + fppath = path + '/' + fp + if(os.path.isfile(fppath)): + files.append(fppath) + elif(os.path.isdir(fppath)): + files += get_files(fppath) + return files + +# Count lines and blank lines and note lines in designated files +def count_lines(files): + line, blank, note = 0, 0, 0 + for filename in files: + f = open(filename, 'rb') + for l in f: + l = l.strip() + line += 1 + if l == '': + blank += 1 + elif l[0] == '#' or l[0] == '/': + note += 1 + f.close() + return (line, blank, note) + +if __name__ == '__main__': + files = get_files('.') + print files + lines = count_lines(files) + print 'Line(s): %d, black line(s): %d, note line(s): %d' % (lines[0], lines[1], lines[2]) diff --git a/DIYgod/0007/test.py b/DIYgod/0007/test.py new file mode 100644 index 00000000..f61ff024 --- /dev/null +++ b/DIYgod/0007/test.py @@ -0,0 +1,41 @@ +# -*- coding: utf-8 -*- + +import re +import os + +# Get all files in designated path +def get_files(path): + filepath = os.listdir(path) + files = [] + for fp in filepath: + fppath = path + '/' + fp + if(os.path.isfile(fppath)): + files.append(fppath) + elif(os.path.isdir(fppath)): + files += get_files(fppath) + return files + +# Get the most popular word in designated files +def get_important_word(files): + worddict = {} + for filename in files: + f = open(filename, 'rb') + s = f.read() + words = re.findall(r'[a-zA-Z0-9]+', s) + for word in words: + worddict[word] = worddict[word] + 1 if word in worddict else 1 + wordsort = sorted(worddict.items(), key=lambda e:e[1], reverse=True) + return wordsort + +if __name__ == '__main__': + files = get_files('.') + print files + wordsort = get_important_word(files) + maxnum = 1 + for i in range(len(wordsort) - 1): + if wordsort[i][1] == wordsort[i + 1][1]: + maxnum += 1 + else: + break + for i in range(maxnum): + print wordsort[i] diff --git a/DIYgod/0007/test/test.py b/DIYgod/0007/test/test.py new file mode 100644 index 00000000..f61ff024 --- /dev/null +++ b/DIYgod/0007/test/test.py @@ -0,0 +1,41 @@ +# -*- coding: utf-8 -*- + +import re +import os + +# Get all files in designated path +def get_files(path): + filepath = os.listdir(path) + files = [] + for fp in filepath: + fppath = path + '/' + fp + if(os.path.isfile(fppath)): + files.append(fppath) + elif(os.path.isdir(fppath)): + files += get_files(fppath) + return files + +# Get the most popular word in designated files +def get_important_word(files): + worddict = {} + for filename in files: + f = open(filename, 'rb') + s = f.read() + words = re.findall(r'[a-zA-Z0-9]+', s) + for word in words: + worddict[word] = worddict[word] + 1 if word in worddict else 1 + wordsort = sorted(worddict.items(), key=lambda e:e[1], reverse=True) + return wordsort + +if __name__ == '__main__': + files = get_files('.') + print files + wordsort = get_important_word(files) + maxnum = 1 + for i in range(len(wordsort) - 1): + if wordsort[i][1] == wordsort[i + 1][1]: + maxnum += 1 + else: + break + for i in range(maxnum): + print wordsort[i] diff --git a/DIYgod/README.md b/DIYgod/README.md new file mode 100644 index 00000000..90f9d4f4 --- /dev/null +++ b/DIYgod/README.md @@ -0,0 +1 @@ +Python 练习册,每天一个小程序,所有题目点击这里查看:https://github.com/Show-Me-the-Code/show-me-the-code diff --git a/Dineshkarthik/0001/activation_code.py b/Dineshkarthik/0001/activation_code.py new file mode 100644 index 00000000..026d9b5e --- /dev/null +++ b/Dineshkarthik/0001/activation_code.py @@ -0,0 +1,17 @@ +#!/usr/local/bin/python +#coding=utf-8 +__author__ = 'Dineshkarthik' + +#0001 Title: As Apple Store App independent developer, you engage in limited-time promotion for your application to generate activation code (or coupon), how to use Python to generate 200 activation code (or coupon)? + +import uuid + +def act_code(count): + f = open('code.txt', 'wb') + for i in range(count): + s = str(uuid.uuid4().get_hex().lower()[0:8]) + f.write(''.join(s) + '\n') + f.close() + +if __name__ == '__main__': + act_code(200) diff --git a/Dineshkarthik/0003/0003.py b/Dineshkarthik/0003/0003.py new file mode 100644 index 00000000..1a2d620b --- /dev/null +++ b/Dineshkarthik/0003/0003.py @@ -0,0 +1,17 @@ +#!/usr/local/bin/python +#coding=utf-8 +__author__ = 'Dineshkarthik' + +#0003 Title: The 0001 title generated 200 activation code (or coupon) to save Redis non-relational databases. + +from walrus import * + +def redis_store(count): + db=Database(host='localhost',port=6379,db=0) + h = db.List("activation_code") + for i in range(count): + s = str(uuid.uuid4().get_hex().lower()[0:8]) + h.extend([s]) + +if __name__ == '__main__': + redis_store(200) \ No newline at end of file diff --git a/Dineshkarthik/0004/0004.py b/Dineshkarthik/0004/0004.py new file mode 100644 index 00000000..3b0440e4 --- /dev/null +++ b/Dineshkarthik/0004/0004.py @@ -0,0 +1,27 @@ +#!/usr/local/bin/python +#coding=utf-8 +__author__ = 'Dineshkarthik' + +#0004 Title: any of a plain text file in English, statistics on the number of words appears. + +import pandas as pd +import re + +def word_count(file_path): + word_string = [line.rstrip('\n') for line in open(file_path)] + words = [] + for word in word_string: + tt = word.lower() + t=re.sub(r'[^\w]', ' ', tt) + for word in t.split(): + words.append(word) + + p = pd.Series(words) + #get the counts per word + freq = p.value_counts() + #how many max words do we want to give back + freq = freq.ix[0:25] + print freq +if __name__ == '__main__': + word_count("input.txt") + \ No newline at end of file diff --git a/Dineshkarthik/0004/input.txt b/Dineshkarthik/0004/input.txt new file mode 100644 index 00000000..06cdebc4 --- /dev/null +++ b/Dineshkarthik/0004/input.txt @@ -0,0 +1,9 @@ +Python Workbook, a small daily program + +Explanation: + +Python Workbook, a small daily program. Note: Python into other languages, most of the topics also apply +Do not appear, such as "print multiplication table", "Print Narcissus" like topic +In this paper, the history of this paper by the @ Jiang Song ( shijiangge@gmail.com QQ: 499 065 469) according to organize data collection from the Internet, thanks to the Internet, thanks for sharing. Thanks! This article will be updated continuously. +Welcome to the Pull Request a problem, paste the code (Gist, Blog can be) :-) +Welcome to answer, and send pull request to the Show-Me-the-Code \ No newline at end of file diff --git a/Dineshkarthik/0006/0006.py b/Dineshkarthik/0006/0006.py new file mode 100644 index 00000000..d850f1c4 --- /dev/null +++ b/Dineshkarthik/0006/0006.py @@ -0,0 +1,35 @@ +#!/usr/local/bin/python +#coding=utf-8 +__author__ = 'Dineshkarthik' + +#0006 title: Do you have a catalog, you put a month's diary, they are txt, word in order to avoid the problem, assuming that the content is in English, see the statistics of each diary you think the most important word. + +import re +import pandas as pd +import glob +import fnmatch +import os + +def word_count(file_path): + data = [] + for root, dirnames, filenames in os.walk(file_path): + for filename in fnmatch.filter(filenames, '/*.txt'): + data.append([line.rstrip('\n') for line in open(os.path.join(root, filename))]) + word_string = ["".join(str(x) for x in data)] + words = [] + ignore_words = ["omitted", "media","a","able","about","above","abst","accordance","according","accordingly","across","act","actually","added","adj","affected","affecting","affects","after","afterwards","again","against","ah","airport","alarm","alive","all","almost","alone","along","already","also","although","always","am","among","amongst","an","and","angry","announce","another","answer","any","anybody","anyhow","anymore","anyone","anything","anyway","anyways","anywhere","apart","app","apparently","application","approximately","are","aren","arent","arise","arm","around","as","aside","ask","asking","at","auth","available","away","awfully","b","back","bad","bag","bake","bar","be","became","because","become","becomes","becoming","been","beer","before","beforehand","begin","beginning","beginnings","begins","behind","being","believe","bell","below","bend","beside","besides","between","beyond","bike","bill","biol","bite","boose","boss","both","brief","brief","briefly","bro","buddy","busy","but","button","by","c","ca","calculate","calculated","call","called","calm","came","can","can't","cannot","cat","cause","causes","certain","certainly","chat","chair","channel","check","close","closing","clue","co","code","coffee","com","come","comes","company","complete","completed","congrats","contain","containing","contains","could","couldnt","cow","crash","cross","d","da","dai","data","database","date","daughter","day","db","delete","deleted","desk","did","didn't","diet","different","dinner","do","does","doesn't","dog","doing","don't","done","down","downwards","drive","dude","due","during","e-mail","e","each","ear","ear","ears","ease","east","easy","ed","edu","effect","eg","eh","eight","eighty","either","else","elsewhere","email","emp","empty","end","ending","enough","error","especially","et-al","et","etc","even","evening","ever","every","everybody","everyone","everything","everywhere","ex","except","exciting","eye","eyes","f","far","fault","female","few","ff","fifth","file","first","five","fix","flower","fly","followed","following","follows","food","for","former","formerly","forth","found","four","friday","friend","from","fuck","fun","funny","further","furthermore","g","garbage","gate","gave","gb","get","gets","getting","girl","git","give","given","gives","giving","glove","go","god","goes","gone","good","got","gotten","great","gross","guy","h","ha","had","hair","hall","happens","hardly","has","hasn't","hate","have","haven't","having","he","hed","hello","hence","her","here","hereafter","hereby","herein","heres","hereupon","hers","herself","hes","hi","hid","high","him","himself","his","hither","ho","holy","home","hope","how","howbeit","however","hundred","husband","i","i'll","i've","id","ie","if","im","image","immediate","immediately","importance","important","in","inc","increase","increased","indeed","index","information","instead","into","invention","inward","iron","is","isn't","it","it'll","itd","its","itself","j","junior","just","k","keep","keeps","kept","kg","kid","kids","km","know","known","knows","l","largely","last","lately","later","latter","latterly","laugh","least","leave","leg","legs","less","lest","let","lets","life","like","liked","likely","line","list","little","ll","load","lol","look","looking","looks","lost","loud","love","low","ltd","lucky","lunch","m","ma'am","maam","madam","made","mail","mainmainly","make","makes","male","mam","many","marry","matemay","maybe","mb","me","meal","meals","mean","means","meantime","meanwhile","men","menu","merely","message","mg","might","million","mineral","miss","ml","mobile","monday","monthly","more","moreover","morning","most","mostly","move","movie","mr","mrs","much","mug","must","my","myself","n","na","name","named","namely","nay","nd","near","nearly","necessarily","necessary","need","needs","neither","never","nevertheless","new","next","nine","ninety","no","nobody","noise","non","none","nonetheless","noone","nor","normally","north","nos","not","noted","nothing","now","nowhere","np","o","obtain","obtained","obviously","of","off","offer","often","oh","ok","okay","old","omitted","on","once","one","ones","only","onto","open","opening","or","ord","other","others","otherwise","ought","our","ours","ourselves","out","outside","over","overall","owing","own","p","page","pages","part","particular","particularly","past","pattern","pause","pay","pays","pencil","per","perhaps","phone","photo","picture","ping","placed","play","please","pls","plus","pong","poorly","possible","possibly","potentially","pp","predominantly","present","previously","primarily","pro","probably","promise","promptly","proof","proud","provides","pull","push","put","q","que","quickly","quiet","quit","quite","qv","r","ran","rather","ratio","rd","re","readily","really","recent","recently","ref","refs","regarding","regardless","regards","related","relatively","reload","reply","research","respectively","restraunt","resulted","resulting","results","right","rock","rofl","roll","run","s","said","same","saturday","saw","say","saying","says","script","sec","section","see","seeing","seem","seemed","seeming","seems","seen","self","selves","send","senior","sent","sent","seven","several","shall","she","she'll","shed","shes","shit","shock","should","shouldn't","show","showed","shown","showns","shows","shut","significant","significantly","similar","similarly","since","sir","sirr","six","slightly","slip","smoke","so","some","somebody","somehow","someone","somethan","something","sometime","sometimes","somewhat","somewhere","son","song","soon","sorry","sort","sound","south","specifically","specified","specify","specifying","sport","sports","still","stop","story","strongly","sub","substantially","successfully","such","sufficiently","suggest","sunday","sup","super","superb","sure","take","taken","taking","tall","tea","team","tear","tell","temporary","tends","term","test","text","th","than","thank","thanks","thanx","that","that'll","that've","thats","the","their","theirs","them","themselves","then","thence","there","there'll","there've","thereafter","thereby","thered","therefore","therein","thereof","therere","theres","thereto","thereupon","these","they","they'll","they've","theyd","theyre","thing","think","this","those","thou","though","thoughh","thousand","throat","throug","through","throughout","thru","thursday","thus","tight","til","till","time","tiny","tip","to","today","toe","together","too","took","tooth","toward","towards","tower","town","translate","tried","tries","truck","truly","trust","try","trying","ts","tuesday","twice","two","u","un","under","unfair","unfortunately","unless","unlike","unlikely","until","unto","up","update","updated","upon","upper","ups","us","use","used","useful","usefully","usefulness","user","uses","using","usually","v","value","various","ve","very","via","visible","viz","vol","vols","volume","vs","w","wake","want","wants","was","wash","wasnt","way","we","we'll","we've","web","website","wed","wednesday","weekend","weekly","welcome","went","were","werent","west","what","what'll","whatever","whats","when","whence","whenever","where","whereafter","whereas","whereby","wherein","wheres","whereupon","wherever","whether","which","while","whim","whither","who","who'll","whod","whoever","whole","whom","whomever","whos","whose","why","widely","wife","will","willing","wish","with","within","without","women","wont","words","work","works","world","would","wouldnt","wrap","wtf","www","x","y","ya","yeah","yep","yes","yesterday","yet","you","you'll","you've","youd","your","youre","yours","yourself","yourselves","youth","z","zero","things","testing","nice","working","messages","issues","issue","refresh","users","upload","download","view","free","kool","uh","duh","join","joining","original","alright","large","entire","start","month","sense","fill"] + for word in word_string: + tt = word.lower() + t=re.sub(r'[^\w]', ' ', tt) + for word in t.split(): + if word not in ignore_words: + words.append(word) + + p = pd.Series(words) + #get the counts per word + freq = p.value_counts() + #how many max words do we want to give back + freq = freq.ix[0:25] + print freq +if __name__ == '__main__': + word_count("/MyDairy") \ No newline at end of file diff --git a/Dineshkarthik/0006/MyDairy/day1.txt b/Dineshkarthik/0006/MyDairy/day1.txt new file mode 100644 index 00000000..06cdebc4 --- /dev/null +++ b/Dineshkarthik/0006/MyDairy/day1.txt @@ -0,0 +1,9 @@ +Python Workbook, a small daily program + +Explanation: + +Python Workbook, a small daily program. Note: Python into other languages, most of the topics also apply +Do not appear, such as "print multiplication table", "Print Narcissus" like topic +In this paper, the history of this paper by the @ Jiang Song ( shijiangge@gmail.com QQ: 499 065 469) according to organize data collection from the Internet, thanks to the Internet, thanks for sharing. Thanks! This article will be updated continuously. +Welcome to the Pull Request a problem, paste the code (Gist, Blog can be) :-) +Welcome to answer, and send pull request to the Show-Me-the-Code \ No newline at end of file diff --git a/Dineshkarthik/0006/MyDairy/day2.txt b/Dineshkarthik/0006/MyDairy/day2.txt new file mode 100644 index 00000000..4c746f45 --- /dev/null +++ b/Dineshkarthik/0006/MyDairy/day2.txt @@ -0,0 +1,2 @@ +To change the file object’s position, use f.seek(offset, from_what). The position is computed from adding offset to a reference point; the reference point is selected by the from_what argument. +A from_what value of 0 measures from the beginning of the file, 1 uses the current file position, and 2 uses the end of the file as the reference point. from_what can be omitted and defaults to 0, using the beginning of the file as the reference point. \ No newline at end of file diff --git a/Dineshkarthik/0006/MyDairy/day3.txt b/Dineshkarthik/0006/MyDairy/day3.txt new file mode 100644 index 00000000..5c7f2f69 --- /dev/null +++ b/Dineshkarthik/0006/MyDairy/day3.txt @@ -0,0 +1 @@ +In text files (those opened without a b in the mode string), only seeks relative to the beginning of the file are allowed (the exception being seeking to the very file end with seek(0, 2)) and the only valid offset values are those returned from the f.tell(), or zero. Any other offset value produces undefined behaviour. \ No newline at end of file diff --git a/Dineshkarthik/0008/0008.py b/Dineshkarthik/0008/0008.py new file mode 100644 index 00000000..0199b378 --- /dev/null +++ b/Dineshkarthik/0008/0008.py @@ -0,0 +1,15 @@ +#!/usr/local/bin/python +#coding=utf-8 +__author__ = 'Dineshkarthik' + +#0008 Title: an HTML file, find the inside of the body . + + +import urllib2 +from bs4 import BeautifulSoup + +url = "https://www.google.co.in" +page = urllib2.urlopen(url) + +soup = BeautifulSoup(page) +print soup.body.text \ No newline at end of file diff --git a/Dineshkarthik/0009/0009.py b/Dineshkarthik/0009/0009.py new file mode 100644 index 00000000..c8b50432 --- /dev/null +++ b/Dineshkarthik/0009/0009.py @@ -0,0 +1,17 @@ +#!/usr/local/bin/python +#coding=utf-8 +__author__ = 'Dineshkarthik' + +#0008 Title: an HTML file, find the inside of the link . + + +import urllib2 +from bs4 import BeautifulSoup + +url = "https://www.google.com" +page = urllib2.urlopen(url) + +soup = BeautifulSoup(page) +links = soup.findAll('a') +for link in links: + print(link['href']) \ No newline at end of file diff --git a/Drake-Z/0000/0000.py b/Drake-Z/0000/0000.py new file mode 100644 index 00000000..857e7480 --- /dev/null +++ b/Drake-Z/0000/0000.py @@ -0,0 +1,24 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- + +'第 0000 题:将你的 QQ 头像(或者微博头像)右上角加上红色的数字,类似于微信未读信息数量那种提示效果。' + +__author__ = 'Drake-Z' + +from PIL import Image, ImageDraw, ImageFont + +def add_num(filname, text = '4', fillcolor = (255, 0, 0)): + img = Image.open(filname) + width, height = img.size + myfont = ImageFont.truetype('C:/windows/fonts/Arial.ttf', size=width//8) + fillcolor = (255, 0, 0) + draw = ImageDraw.Draw(img) + draw.text((width-width//8, 0), text, font=myfont, fill=fillcolor) + img.save('1.jpg','jpeg') + return 0 + +if __name__ == '__main__': + filname = '0.jpg' + text = '4' + fillcolor = (255, 0, 0) + add_num(filname, text, fillcolor) \ No newline at end of file diff --git a/Drake-Z/0001/0001.py b/Drake-Z/0001/0001.py new file mode 100644 index 00000000..4d6b4925 --- /dev/null +++ b/Drake-Z/0001/0001.py @@ -0,0 +1,24 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- + +'第 0001 题:做为 Apple Store App 独立开发者,你要搞限时促销,为你的应用生成激活码(或者优惠券),使用 Python 如何生成 200 个激活码(或者优惠券)' + +__author__ = 'Drake-Z' + +import random + +def randChar(filename, digit=4, num=200): + f = open(filename, 'a') + for i in range(0, num): + for m in range(0, digit): + f.write(chr(random.randint(65, 90))) + f.write('\n') + f.close() + print('Done!') + return 0 + +if __name__ == '__main__': + filename = 'active_code.txt' + digit = 4 + num = 200 + rndChar(filename, digit, num) \ No newline at end of file diff --git a/Drake-Z/0002/0002.py b/Drake-Z/0002/0002.py new file mode 100644 index 00000000..34f28723 --- /dev/null +++ b/Drake-Z/0002/0002.py @@ -0,0 +1,37 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- + +'第 0002 题:将 0001 题生成的 200 个激活码(或者优惠券)保存到 MySQL 关系型数据库中。' + +__author__ = 'Drake-Z' + +import mysql.connector + +def write_to_mysql(filename): + conn = mysql.connector.connect(user='root', password='986535', database='test') + cursor = conn.cursor() + cursor.execute("DROP TABLE IF EXISTS user") + cursor.execute('create table user (id varchar(20) primary key, name varchar(20))') + f = open(filename, 'r').readlines() + for line, num in zip(f, range(1, len(f)+1)): + line = line[:-1] #去除\n符号 + cursor.execute('insert into user (id, name) values (%s, %s)', [str(num), line]) + conn.commit() + cursor.close() + return 0 + +def search_mysql(): + b = input('Search Active code(1-200):') + conn = mysql.connector.connect(user='root', password='986535', database='test') + cursor = conn.cursor() + cursor.execute('select * from user where id = %s', (b,)) + values = cursor.fetchall() + print(values) + cursor.close() + conn.close() + return 0 + +if __name__ == '__main__': + filename = 'active_code.txt' + write_to_mysql(filename) + search_mysql() \ No newline at end of file diff --git a/Drake-Z/0003/0003.py b/Drake-Z/0003/0003.py new file mode 100644 index 00000000..d0ab4bf4 --- /dev/null +++ b/Drake-Z/0003/0003.py @@ -0,0 +1,28 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- + +'第 0003 题:将 0001 题生成的 200 个激活码(或者优惠券)保存到 Redis 非关系型数据库中。' + +__author__ = 'Drake-Z' + +import redis + +def write_to_redis(filename): + r = redis.StrictRedis(host='localhost', port=6379, db=0) + r.flushdb() + f = open(filename, 'r').readlines() + for line, num in zip(f, range(1, len(f)+1)): + line = line[:-1] #去除\n符号 + r.set(num, line) + return 0 + +def search_redis(): + b = int(input('Search Active code(1-200):')) + r = redis.StrictRedis(host='localhost', port=6379, db=0) + print(str(r.get(b),'UTF-8')) + return 0 + +if __name__ == '__main__': + filename = 'active_code.txt' + write_to_redis(filename) + search_redis() \ No newline at end of file diff --git a/Drake-Z/0004/0004.py b/Drake-Z/0004/0004.py new file mode 100644 index 00000000..9deb26b1 --- /dev/null +++ b/Drake-Z/0004/0004.py @@ -0,0 +1,18 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- + +'第 0004 题:任一个英文的纯文本文件,统计其中的单词出现的个数。' + +__author__ = 'Drake-Z' + +import re + +def statistics(file_path): + f = open(file_path, 'r').read() + f = re.findall(r'[\w\-\_\.\']+', f) + print(len(f)) + return 0 + +if __name__ == '__main__': + file_path = 'English.txt' + statistics(file_path) \ No newline at end of file diff --git a/Drake-Z/0004/English.txt b/Drake-Z/0004/English.txt new file mode 100644 index 00000000..197d3b49 --- /dev/null +++ b/Drake-Z/0004/English.txt @@ -0,0 +1,2 @@ +ConnectionPools manage a set of Connection instances. redis-py ships with two types of Connections. The default, Connection, is a normal TCP socket based connection. The UnixDomainSocketConnection allows for clients running on the same device as the server to connect via a unix domain socket. +To use a, UnixDomainSocketConnection connection, simply pass the unix_socket_path argument, which is a string to the unix domain socket file. Additionally, make sure the unixsocket parameter is defined in your redis.conf file. It's commented out by default. \ No newline at end of file diff --git a/Drake-Z/0005/0005.py b/Drake-Z/0005/0005.py new file mode 100644 index 00000000..e3d5ec85 --- /dev/null +++ b/Drake-Z/0005/0005.py @@ -0,0 +1,24 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- + +'第 0005 题:你有一个目录,装了很多照片,把它们的尺寸变成都不大于 iPhone5 分辨率(1136x640)的大小。' + +__author__ = 'Drake-Z' + +import os +import glob +from PIL import Image + +def thumbnail_pic(path): + a = glob.glob(r'*.jpg') + for x in a: + name = os.path.join(path, x) + im = Image.open(name) + im.thumbnail((1136, 640)) + print(im.format, im.size, im.mode) + im.save(name, 'JPEG') + print('Done!') + +if __name__ == '__main__': + path = '.' + thumbnail_pic(path) \ No newline at end of file diff --git a/Drake-Z/0005/ace-94.jpg b/Drake-Z/0005/ace-94.jpg new file mode 100644 index 00000000..636d9e94 Binary files /dev/null and b/Drake-Z/0005/ace-94.jpg differ diff --git a/Drake-Z/0006/0006.py b/Drake-Z/0006/0006.py new file mode 100644 index 00000000..4d120596 --- /dev/null +++ b/Drake-Z/0006/0006.py @@ -0,0 +1,38 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- + +'第 0004 题:任一个英文的纯文本文件,统计其中的单词出现的个数。' + +__author__ = 'Drake-Z' + +import os +import re +import glob +from collections import OrderedDict + +def get_num(key_word, filename): + '''获得词汇出现次数''' + f = open(filename, 'r', encoding='utf-8').read() + re_zhengze = re.compile(r'[\s\,\;\.\n]{1}'+key_word+r'[\s\,\;\.\n]{1}') + numbers = re_zhengze.findall(f) + return len(numbers) + +def article_analysis(dirs): + article = glob.glob(r'*.txt') + dictdata = OrderedDict() + for m in article: + doc = open(m, 'r', encoding='utf-8').read() + doc = re.findall(r'[\w\-\_\.\']+', doc) #获得单词list + doc = list(map(lambda x: x.strip('.'), doc)) #去除句号 + for n in doc: + dictdata[n] = get_num(n, m) + a = OrderedDict(sorted(dictdata.items(), key=lambda x: x[1], reverse = True)) #dict排序 + print('在 %s 中出现次数最多的单词是:' % m) + for c in a: + print(c+' : %s 次' % a[c]) + break + return 0 + +if __name__ == '__main__': + file = '.' + article_analysis(file) diff --git a/Drake-Z/0006/001.txt b/Drake-Z/0006/001.txt new file mode 100644 index 00000000..53eff756 --- /dev/null +++ b/Drake-Z/0006/001.txt @@ -0,0 +1 @@ +You are not so absorbed about them. You see them for their flaws and perfections. Since you can rely on your instincts and find other pleasures, rather than just within the relationship itself, you understand your partner better. This knowledge will prove beneficial in the way you treat them. \ No newline at end of file diff --git a/Drake-Z/0006/002.txt b/Drake-Z/0006/002.txt new file mode 100644 index 00000000..e4d26f04 --- /dev/null +++ b/Drake-Z/0006/002.txt @@ -0,0 +1,3 @@ +Being in a relationship can be a full-time job. Sometimes, it can become so overwhelming and consuming that you lose your own voice and sense of ownership. You want freedom and you think your partner is not making you happy enough. You question why you are in the relationship at all. + +Yes, we all need that moment to feel uneasy and track our direction in whatever relationship we’re in. These breaks can be beneficial to becoming the person you want to be. Here are some of the positive things that can come out of those moments of indecision. \ No newline at end of file diff --git a/Drake-Z/0006/003.txt b/Drake-Z/0006/003.txt new file mode 100644 index 00000000..69306767 --- /dev/null +++ b/Drake-Z/0006/003.txt @@ -0,0 +1,4 @@ +Being lost can offer you freedom. You identify your core values, desires, and tastes. You are open with yourself and you can try new things. You understand that you do not have to always rely on your partner. Perhaps there is a movie coming out this weekend, you can buy a ticket and go to the cinemas yourself — something that may have been unheard of for you in the past. Being forced to find this independence can make you a stronger person. +You can disconnect. You are no longer driven by the interests of your partner, but by your own desires. This means getting back to the basics, like reading books by your favorite author, exercising, eating your favorite meals. When you return to these ideals, you are strengthened and become a better you. + +People think that being lost in a relationship signals doom for that relationship — it doesn’t. It all depends on how you manage this necessary stage and work towards making the most of it. \ No newline at end of file diff --git a/Drake-Z/0007/0007.py b/Drake-Z/0007/0007.py new file mode 100644 index 00000000..53a1cd3a --- /dev/null +++ b/Drake-Z/0007/0007.py @@ -0,0 +1,45 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- + +'第 0007 题:有个目录,里面是你自己写过的程序,统计一下你写过多少行代码。包括空行和注释,但是要分别列出来。' + +__author__ = 'Drake-Z' + +import os +import re + +def count_num(a, b): + shuzi = [0, 0, 0] + path = os.path.join(a, b) + f = open(path, 'r', encoding='UTF-8').readlines() + for i in f: + if re.match(r'^#', i) == None: + pass + else: + shuzi[1] += 1 #获得注释行数,只匹配单行注释 + if f[-1][-1:]=='\n': #最后一行为空行时 + shuzi[2] = f.count('\n')+1 #获得空行行数 + shuzi[0] = len(f)+1 - shuzi[2] - shuzi[1] #获得代码行数 + else: + shuzi[2] = f.count('\n') + shuzi[0] = len(f) - shuzi[2] - shuzi[1] + return shuzi + +def file_analysis(c, d): + py = [x for x in os.listdir(c) if os.path.splitext(x)[1]==d] #获得文件列表 + print(py) + the_num = [0, 0, 0] + for i in py: + num = count_num(c, i) + the_num[0] += num[0] #累计 + the_num[1] += num[1] + the_num[2] += num[2] + print('''统计得目录中: + 代码有 %s 行 + 注释 %s 行 + 空行 %s 行''' % (the_num[0], the_num[1], the_num[2])) + +if __name__ == '__main__': + file = '.' + ext = '.py' + file_analysis(file, ext) \ No newline at end of file diff --git a/Drake-Z/0007/test.py b/Drake-Z/0007/test.py new file mode 100644 index 00000000..f66f4a56 --- /dev/null +++ b/Drake-Z/0007/test.py @@ -0,0 +1,41 @@ +# -*- coding: utf-8 -*- +# mydict_test.py + +import unittest +from MyMoudel.Moudel1 import Dict +class TestDict(unittest.TestCase): + + def test_init(self): + d = Dict(a=1, b='test') + self.assertEqual(d.a, 1) + self.assertEqual(d.b, 'test') + self.assertTrue(isinstance(d, dict)) + + def test_key(self): + d = Dict() + d['key'] = 'value' + self.assertEqual(d.key, 'value') + + def test_attr(self): + d = Dict() + d.key = 'value' + self.assertTrue('key' in d) + self.assertEqual(d['key'], 'value') + + def test_keyerror(self): + d = Dict() + with self.assertRaises(KeyError): + value = d['empty'] + + def test_attrerror(self): + d = Dict() + with self.assertRaises(AttributeError): + value = d.empty + + def setUp(self): + print('setUp...') + + def tearDown(self): + print('tearDown...') +if __name__ == '__main__': + unittest.main() \ No newline at end of file diff --git a/Drake-Z/0008/0008.py b/Drake-Z/0008/0008.py new file mode 100644 index 00000000..009a2712 --- /dev/null +++ b/Drake-Z/0008/0008.py @@ -0,0 +1,33 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- + +'第 0008 题:一个HTML文件,找出里面的正文。' + +__author__ = 'Drake-Z' + +from html.parser import HTMLParser +from html.entities import name2codepoint + +class MyHTMLParser(HTMLParser): + in_zhengwen = False + in_huanhang = False + def handle_starttag(self, tag, attrs): + if ('class', 'zh-summary summary clearfix') in attrs and tag=='div' : + self.in_zhengwen = True + elif ('class', 'zm-editable-content clearfix') in attrs and tag=='div' : + self.in_zhengwen = True + elif tag=='br': + print('\n') + else: + self.in_zhengwen = False + + def handle_data(self, data): + if self.in_zhengwen: + print(data.strip()) + else: + pass + +if __name__ == '__main__': + parser = MyHTMLParser() + f = open('test.html', 'r', encoding = 'utf-8').read() + parser.feed(f) \ No newline at end of file diff --git a/Drake-Z/0009/0009.py b/Drake-Z/0009/0009.py new file mode 100644 index 00000000..19975694 --- /dev/null +++ b/Drake-Z/0009/0009.py @@ -0,0 +1,24 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- + +'第 0009 题:一个HTML文件,找出里面的链接。' + +__author__ = 'Drake-Z' + +import os, re +from html.parser import HTMLParser +from html.entities import name2codepoint + +class MyHTMLParser(HTMLParser): + + def handle_starttag(self, tag, attrs): + if tag == 'a': + for (variables, value) in attrs: + if variables == 'href': + if re.match(r'http(.*?)', value): + print(value) + +if __name__ == '__main__': + with open('test.html', encoding='utf-8') as html: + parser = MyHTMLParser() + parser.feed(html.read()) \ No newline at end of file diff --git a/Drake-Z/0010/0010.py b/Drake-Z/0010/0010.py new file mode 100644 index 00000000..d229f45e --- /dev/null +++ b/Drake-Z/0010/0010.py @@ -0,0 +1,39 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- + +'第 0010 题:使用 Python 生成类似于图中的字母验证码图片' + +from PIL import Image, ImageDraw, ImageFont, ImageFilter + +import random + +# 随机字母: +def rndChar(): + return chr(random.randint(65, 90)) + +# 随机颜色1: +def rndColor(): + return (random.randint(64, 255), random.randint(64, 255), random.randint(64, 255)) + +# 随机颜色2: +def rndColor2(): + return (random.randint(32, 127), random.randint(32, 127), random.randint(32, 127)) + +# 240 x 60: +width = 60 * 4 +height = 60 +image = Image.new('RGB', (width, height), (255, 255, 255)) +# 创建Font对象: +font = ImageFont.truetype('C:\Windows\Fonts\Arial.ttf', 36) +# 创建Draw对象: +draw = ImageDraw.Draw(image) +# 填充每个像素: +for x in range(width): + for y in range(height): + draw.point((x, y), fill=rndColor()) +# 输出文字: +for t in range(4): + draw.text((60 * t + 10, 10), rndChar(), font=font, fill=rndColor2()) +# 模糊: +image = image.filter(ImageFilter.BLUR) +image.save('0010\code.jpg', 'jpeg') \ No newline at end of file diff --git a/Drake-Z/0011/0011.py b/Drake-Z/0011/0011.py new file mode 100644 index 00000000..510f3e92 --- /dev/null +++ b/Drake-Z/0011/0011.py @@ -0,0 +1,22 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- + +'第 0011 题: 敏感词文本文件 filtered_words.txt,里面的内容为以下内容,当用户输入敏感词语时,则打印出 Freedom,否则打印出 Human Rights。' + +__author__ = 'Drake-Z' + +import os +import re + +def filter_word(a): + + f = open('filtered_words.txt', 'r', encoding = 'utf-8').read() + if a == '': + print('Human Rights !') + elif len(re.findall(r'%s' % (a), f)) == 0: + print('Human Rights !') #非敏感词时,则打印出 Human Rights ! + else: + print('Freedom !') #输入敏感词语打印出 Freedom ! + +z = input('请输入词语:') +filter_word(z) \ No newline at end of file diff --git a/Drake-Z/0011/filtered_words.txt b/Drake-Z/0011/filtered_words.txt new file mode 100644 index 00000000..69373b64 --- /dev/null +++ b/Drake-Z/0011/filtered_words.txt @@ -0,0 +1,11 @@ +北京 +程序员 +公务员 +领导 +牛比 +牛逼 +你娘 +你妈 +love +sex +jiangge \ No newline at end of file diff --git a/Drake-Z/0012/0012.py b/Drake-Z/0012/0012.py new file mode 100644 index 00000000..e0f2fadf --- /dev/null +++ b/Drake-Z/0012/0012.py @@ -0,0 +1,31 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- + +'第 0012 题: 敏感词文本文件 filtered_words.txt,里面的内容 和 0011题一样,当用户输入敏感词语,则用 星号 * 替换,例如当用户输入「北京是个好城市」,则变成「**是个好城市」。' + +__author__ = 'Drake-Z' + +import os +import re + +def filter_word(a): + sensitive = False + strs = '**' + f = open('filtered_words.txt', 'r', encoding = 'utf-8').readlines() + for i in f: + i = i.strip() #去除\n + b = re.split(r'%s' % (i), a) #分解字符串 + if len(b) > 1: + c = i + sensitive = True + else: + pass + if sensitive == True: + b = re.split(r'%s' % (c.strip()), a) + print(strs.join(b)) + else: + print(a) + return 0 + +z = input('请输入:') +filter_word(z) \ No newline at end of file diff --git a/Drake-Z/0012/filtered_words.txt b/Drake-Z/0012/filtered_words.txt new file mode 100644 index 00000000..69373b64 --- /dev/null +++ b/Drake-Z/0012/filtered_words.txt @@ -0,0 +1,11 @@ +北京 +程序员 +公务员 +领导 +牛比 +牛逼 +你娘 +你妈 +love +sex +jiangge \ No newline at end of file diff --git a/Drake-Z/0013/0013.py b/Drake-Z/0013/0013.py new file mode 100644 index 00000000..f3a17d30 --- /dev/null +++ b/Drake-Z/0013/0013.py @@ -0,0 +1,45 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- + +'第 0013 题: 用 Python 写一个爬图片的程序,爬(http://tieba.baidu.com/p/2166231880)图片 :-)' + +__author__ = 'Drake-Z' + +import os +import re +import urllib +from urllib import request +from urllib.request import urlopen + +def read_url(yuanshiurl): + req = request.Request(yuanshiurl) + req.add_header('User-Agent', 'Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; Trident/4.0; InfoPath.2; .NET4.0C; .NET4.0E; .NET CLR 2.0.50727; 360SE /360/ /chrome/ig)') + with request.urlopen(req) as f: + Imageurl(f.read().decode('utf-8')) #输出Data + return 0 + +def Imageurl(data): + re_Imageurl = re.compile(r'src="(http://imgsrc.baidu.com/forum/.*?)"') + data = re_Imageurl.findall(data) #输出图片链接 + downloadImage(data) + +def downloadImage(pic_url): + dirct = '0013' + try: + if not os.path.exists(dirct): #创建存放目录 + os.mkdir(dirct) + except: + print('Failed to create directory in %s' % dirct) + exit() + for i in pic_url: + data = urllib.request.urlopen(i).read() + i = re.split('/', i)[-1] + print(i) + path = dirct + '/' +i + f = open(path, 'wb') + f.write(data) + f.close() + print('Done !') + +url = 'http://tieba.baidu.com/p/2166231880' +read_url(url) \ No newline at end of file diff --git a/Drake-Z/0014/0014.py b/Drake-Z/0014/0014.py new file mode 100644 index 00000000..c0df4222 --- /dev/null +++ b/Drake-Z/0014/0014.py @@ -0,0 +1,31 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- + +'''第 0014 题: 纯文本文件 student.txt为学生信息, 里面的内容(包括花括号)如下所示: +{ + "1":["张三",150,120,100], + "2":["李四",90,99,95], + "3":["王五",60,66,68] +} +请将上述内容写到 student.xls 文件中。''' + +__author__ = 'Drake-Z' + +import json +from collections import OrderedDict +from openpyxl import Workbook + +def txt_to_xlsx(filename): + file = open(filename, 'r', encoding = 'UTF-8') + file_cintent = json.load(file, encoding = 'UTF-8') + print(file_cintent) + workbook = Workbook() + worksheet = workbook.worksheets[0] + for i in range(1, len(file_cintent)+1): + worksheet.cell(row = i, column = 1).value = i + for m in range(0, len(file_cintent[str(i)])): + worksheet.cell(row = i, column = m+2).value = file_cintent[str(i)][m] + workbook.save(filename = 'student.xls') + +if __name__ == '__main__': + txt_to_xlsx('student.txt') diff --git a/Drake-Z/0015/0015.py b/Drake-Z/0015/0015.py new file mode 100644 index 00000000..1541d123 --- /dev/null +++ b/Drake-Z/0015/0015.py @@ -0,0 +1,30 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- + +'''第 0015 题: 纯文本文件 city.txt为城市信息, 里面的内容(包括花括号)如下所示: +{ + "1" : "上海", + "2" : "北京", + "3" : "成都" +} +请将上述内容写到 city.xls 文件中。''' + +__author__ = 'Drake-Z' + +import json +from collections import OrderedDict +from openpyxl import Workbook + +def txt_to_xlsx(filename): + file = open(filename, 'r', encoding = 'UTF-8') + file_cintent = json.load(file, encoding = 'UTF-8') + print(file_cintent) + workbook = Workbook() + worksheet = workbook.worksheets[0] + for i in range(1, len(file_cintent)+1): + worksheet.cell(row = i, column = 1).value = i + worksheet.cell(row = i, column = 2).value = file_cintent[str(i)] + workbook.save(filename = 'city.xls') + +if __name__ == '__main__': + txt_to_xlsx('city.txt') \ No newline at end of file diff --git a/Drake-Z/0016/0016.py b/Drake-Z/0016/0016.py new file mode 100644 index 00000000..b815b754 --- /dev/null +++ b/Drake-Z/0016/0016.py @@ -0,0 +1,29 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- + +'''第 0016 题: 纯文本文件 numbers.txt, 里面的内容(包括方括号)如下所示: +[ + [1, 82, 65535], + [20, 90, 13], + [26, 809, 1024] +] +请将上述内容写到 numbers.xls 文件中。''' + +__author__ = 'Drake-Z' + +import json +from openpyxl import Workbook + +def txt_to_xlsx(filename): + file = open(filename, 'r', encoding = 'UTF-8') + file_cintent = json.load(file, encoding = 'UTF-8') + print(file_cintent) + workbook = Workbook() + worksheet = workbook.worksheets[0] + for i in range(1, len(file_cintent)+1): + for m in range(1, len(file_cintent[i-1])+1): + worksheet.cell(row = i, column = m).value = file_cintent[i-1][m-1] + workbook.save(filename = 'numbers.xls') + +if __name__ == '__main__': + txt_to_xlsx('numbers.txt') \ No newline at end of file diff --git a/Drake-Z/0017/0017.py b/Drake-Z/0017/0017.py new file mode 100644 index 00000000..baf773ce --- /dev/null +++ b/Drake-Z/0017/0017.py @@ -0,0 +1,59 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- + +'''第 0017 题: 将 第 0014 题中的 student.xls 文件中的内容写到 student.xml 文件中,如 +下所示: + + + + +{ + "1" : ["张三", 150, 120, 100], + "2" : ["李四", 90, 99, 95], + "3" : ["王五", 60, 66, 68] +} + +''' + +__author__ = 'Drake-Z' + +import xlrd,codecs +from lxml import etree +from collections import OrderedDict + +def read_xls(filename): + data = xlrd.open_workbook(filename) + table = data.sheets()[0] + c = OrderedDict() + for i in range(table.nrows): + c[table.cell(i,0).value] = table.row_values(i)[1:] + return c + +def save_xml(data): + output = codecs.open('student.xml','w','utf-8') + root = etree.Element('root') + student_xml = etree.ElementTree(root) + student = etree.SubElement(root, 'student') + student.append(etree.Comment('学生信息表\n\"id\": [名字,数学,语文,英语]')) + student.text = str(data) + output.write(etree.tounicode(student_xml.getroot())) + output.close() + +if __name__ == '__main__': + file = 'student.xls' + a = read_xls(file) + save_xml(a) + + + + + + + + + + + diff --git a/Drake-Z/0018/0018.py b/Drake-Z/0018/0018.py new file mode 100644 index 00000000..97a6db98 --- /dev/null +++ b/Drake-Z/0018/0018.py @@ -0,0 +1,46 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- + +'''第 0018 题: 将 第 0015 题中的 city.xls 文件中的内容写到 city.xml 文件中,如下所示: + + + + +{ + "1" : "上海", + "2" : "北京", + "3" : "成都" +} + +''' + +__author__ = 'Drake-Z' + +import xlrd,codecs +from lxml import etree +from collections import OrderedDict + +def read_xls(filename): + data = xlrd.open_workbook(filename) + table = data.sheets()[0] + c = OrderedDict() + for i in range(table.nrows): + c[table.cell(i,0).value] = table.row_values(i)[1:] + return c + +def save_xml(data): + output = codecs.open('city.xml','w','utf-8') + root = etree.Element('root') + city_xml = etree.ElementTree(root) + city = etree.SubElement(root, 'city') + city.append(etree.Comment('城市信息')) + city.text = str(data) + output.write(etree.tounicode(city_xml.getroot())) + output.close() + +if __name__ == '__main__': + file = 'city.xls' + a = read_xls(file) + save_xml(a) \ No newline at end of file diff --git a/Drake-Z/0019/0019.py b/Drake-Z/0019/0019.py new file mode 100644 index 00000000..c0fde199 --- /dev/null +++ b/Drake-Z/0019/0019.py @@ -0,0 +1,47 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- + +'''第 0019 题: 将 第 0016 题中的 numbers.xls 文件中的内容写到 numbers.xml 文件中,如下 +所示: + + + + +[ + [1, 82, 65535], + [20, 90, 13], + [26, 809, 1024] +] + +''' + +__author__ = 'Drake-Z' + +import xlrd,codecs +from lxml import etree +from collections import OrderedDict + +def read_xls(filename): + data = xlrd.open_workbook(filename) + table = data.sheets()[0] + c = OrderedDict() + for i in range(table.nrows): + c[table.cell(i,0).value] = table.row_values(i)[1:] + return c + +def save_xml(data): + output = codecs.open('numbers.xml','w','utf-8') + root = etree.Element('root') + numbers_xml = etree.ElementTree(root) + numbers = etree.SubElement(root, 'numbers') + numbers.append(etree.Comment('城市信息')) + numbers.text = str(data) + output.write(etree.tounicode(numbers_xml.getroot())) + output.close() + +if __name__ == '__main__': + file = 'numbers.xls' + a = read_xls(file) + save_xml(a) \ No newline at end of file diff --git a/Drake-Z/0020/0020.py b/Drake-Z/0020/0020.py new file mode 100644 index 00000000..98d2062b --- /dev/null +++ b/Drake-Z/0020/0020.py @@ -0,0 +1,32 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- + +'''第 0020 题: 登陆中国联通网上营业厅 后选择「自助服务」 --> 「详单查询」,然后选择你要查询的时间段,点击「查询」按钮,查询结果页面的最下方,点击「导出」,就会生成类似于 2014年10月01日~2014年10月31日通话详单.xls 文件。写代码,对每月通话时间做个统计。''' + +__author__ = 'Drake-Z' + +import os +import re +import xlrd + +def jishu(file): + data = xlrd.open_workbook(file) + table = data.sheets()[0] + re_timesec = re.compile(r'([\d]+)秒') + re_timemin = re.compile(r'([\d]+)分') + row_nums = table.nrows + numbers = 0 + for i in range(0, row_nums): + a = re_timesec.findall(table.cell(i, 3).value) + b = re_timemin.findall(table.cell(i, 3).value) + if len(a)==0 : pass + else: + numbers += int(a[0]) + if len(b)==0 : pass + else: + numbers += int(b[0])*60 + + print('您本月通话时长总时:%s 分 %s 秒' % (numbers//60, numbers%60)) + +file = '语音通信.xls' +jishu(file) \ No newline at end of file diff --git a/Drake-Z/0021/0021.py b/Drake-Z/0021/0021.py new file mode 100644 index 00000000..bab3c856 --- /dev/null +++ b/Drake-Z/0021/0021.py @@ -0,0 +1,32 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- + +'''第 0021 题: 通常,登陆某个网站或者 APP,需要使用用户名和密码。密码是如何加密后存储起来的呢?请使用 Python 对密码加密。''' + +__author__ = 'Drake-Z' + +import hashlib +from collections import defaultdict +db = {} +db = defaultdict(lambda: 'N/A') #去掉登录可能产生的KeyError + +def get_md5(password): + a = hashlib.md5() + a.update(password . encode('utf-8')) + return (a.hexdigest()) + +def register(username, password): + db[username] = get_md5(password + username + 'the-Salt') + +def login(username, password): + b = get_md5(password + username + 'the-Salt' ) + if b==db[username]: + return True + else: + return False +a = input('注册输入用户名:') +b = input('注册输入密码:') +register(a, b) +a = input('登录输入用户名:') +b = input('登录输入密码:') +print(login(a, b)) \ No newline at end of file diff --git a/Drake-Z/0022/0022.py b/Drake-Z/0022/0022.py new file mode 100644 index 00000000..d7f22de5 --- /dev/null +++ b/Drake-Z/0022/0022.py @@ -0,0 +1,23 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- + +'''第 0022 题: iPhone 6、iPhone 6 Plus 早已上市开卖。请查看你写得 第 0005 题的代码是否可以复用。''' + +__author__ = 'Drake-Z' + +from PIL import Image +import os + +def thumbnail_pic(a, b =1136, c=640): + for x in a: + name = os.path.join('.', x) + im = Image.open(name) + print('Before:'+im.format, im.size, im.mode) + im.thumbnail((b, c)) + print('After:'+im.format, im.size, im.mode) + im.save(name, 'JPEG') + +a = os.listdir('.') +PHONE = {'iPhone5':(1136,640), 'iPhone6':(1134,750), 'iPhone6P':(2208,1242)} +width,height = PHONE['iPhone6'] +thumbnail_pic(a, width, height) \ No newline at end of file diff --git a/Forec/0000/0000.py b/Forec/0000/0000.py new file mode 100644 index 00000000..ba5ceefb --- /dev/null +++ b/Forec/0000/0000.py @@ -0,0 +1,15 @@ +from PIL import Image, ImageDraw, ImageFont + +def add_num(num, fill, font_name): + im = Image.open('in.jpg') + xsize , ysize = im.size + draw = ImageDraw.Draw(im) + text = str(num) + font = ImageFont.truetype(font_name, xsize//3) + draw.text((ysize//5 * 4, 0), text, fill, font) + im.save("out.jpg") + +num = 4 +fill = (255, 0, 255) +font_name = "verdana.ttf" +add_num(num, fill, font_name) \ No newline at end of file diff --git a/Forec/0000/in.jpg b/Forec/0000/in.jpg new file mode 100644 index 00000000..fd4c2424 Binary files /dev/null and b/Forec/0000/in.jpg differ diff --git a/Forec/0000/out.jpg b/Forec/0000/out.jpg new file mode 100644 index 00000000..b176eef3 Binary files /dev/null and b/Forec/0000/out.jpg differ diff --git a/Forec/0000/verdana.ttf b/Forec/0000/verdana.ttf new file mode 100644 index 00000000..59f22739 Binary files /dev/null and b/Forec/0000/verdana.ttf differ diff --git a/Forec/0001/0001.py b/Forec/0001/0001.py new file mode 100644 index 00000000..2b8679d7 --- /dev/null +++ b/Forec/0001/0001.py @@ -0,0 +1,18 @@ +# coding = utf-8 +__author__ = 'forec' +import random + +def make_number( num, length ): + str = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789' + b = set() + i = 0 + while i < num: + ans = '' + for j in range(length): + ans += random.choice(str) + if ans not in b: + b |= {ans} + i += 1 + print(ans) + +make_number( 200, 10) \ No newline at end of file diff --git a/Forec/0002/0002.py b/Forec/0002/0002.py new file mode 100644 index 00000000..7d8287b3 --- /dev/null +++ b/Forec/0002/0002.py @@ -0,0 +1,46 @@ +# coding = utf-8 +__author__ = 'Forec' + +# 保随机码至MySQL + +import pymysql +import random + +def make_number( num, length ): + letters = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789' + dic = set() + i = 0 + while i < num: + str = '' + for j in range(length): + str += random.choice(letters) + if str not in dic: + dic |= {str} + i += 1 + else: + continue + return dic + +def save( dic ): + connect = pymysql.connect( + host = '127.0.0.1', + port = 3306, + user = 'root', + passwd = 'VKDARK' + ) + cur = connect.cursor() + try: + __create = 'create database if not exists test' + cur.execute(__create) + except: + print('database create error') + connect.select_db('test') + __create_table = 'create table if not exists codes(code char(64))' + cur.execute(__create_table) + cur.executemany('insert into codes values(%s)',dic) + + connect.commit() + cur.close() + connect.close() + +save(make_number(200,10)) \ No newline at end of file diff --git a/Forec/0004/0004.py b/Forec/0004/0004.py new file mode 100644 index 00000000..9827c883 --- /dev/null +++ b/Forec/0004/0004.py @@ -0,0 +1,19 @@ +import re +with open('input.txt',"r") as f: + data = f.read() + +words = re.compile(r'([a-zA-Z]+)') +dic = {} +for x in words.findall(data): + if x not in dic: + dic[x] = 1 + else: + dic[x] += 1 +L = [] +for k,value in dic.items(): + L.append((k, value)) + +L.sort(key = lambda t:t[0]) + +for x in L: + print( x[0], x[1]) \ No newline at end of file diff --git a/Forec/0004/input.txt b/Forec/0004/input.txt new file mode 100644 index 00000000..46b559d1 --- /dev/null +++ b/Forec/0004/input.txt @@ -0,0 +1 @@ +I love you baby, so I just love you baby, no matter how fast baby \ No newline at end of file diff --git a/Forec/0005/0005.py b/Forec/0005/0005.py new file mode 100644 index 00000000..ba538f49 --- /dev/null +++ b/Forec/0005/0005.py @@ -0,0 +1,12 @@ +from PIL import Image, ImageOps +import os, os.path + +L = [ x for x in os.listdir('.') if os.path.isfile(x) and os.path.splitext(x)[1]=='.jpg' ] + +for x in L: + img = Image.open(x) + xsize, ysize = img.size + xsize = 500 + ysize = ysize * 500 // xsize + img = ImageOps.fit(img,(xsize,ysize)) + img.save("out"+x) \ No newline at end of file diff --git a/Forec/0006/0006.py b/Forec/0006/0006.py new file mode 100644 index 00000000..631a9e1b --- /dev/null +++ b/Forec/0006/0006.py @@ -0,0 +1,27 @@ +# coding = utf-8 +__author__ = 'Forec' +import os, re + +def find_word(file_path): + file_list = os.listdir(file_path) + word_dic = {} + word_re = re.compile(r'[\w]+') + for x in file_list: + if os.path.isfile(x) and os.path.splitext(x)[1] =='.txt' : + try: + f = open(x, 'r') + data = f.read() + f.close() + words = word_re.findall(data) + for word in words: + if word not in word_dic: + word_dic[word] = 1 + else: + word_dic[word] += 1 + except: + print('Open %s Error' % x) + Ans_List = sorted(word_dic.items(), key = lambda t : t[1], reverse = True) + for key, value in Ans_List: + print( 'Word ', key, 'appears %d times' % value ) + +find_word('.') \ No newline at end of file diff --git a/Forec/0006/1.txt b/Forec/0006/1.txt new file mode 100644 index 00000000..912c1df5 --- /dev/null +++ b/Forec/0006/1.txt @@ -0,0 +1 @@ +I love you Beijing \ No newline at end of file diff --git a/Forec/0006/2.txt b/Forec/0006/2.txt new file mode 100644 index 00000000..b3ed252d --- /dev/null +++ b/Forec/0006/2.txt @@ -0,0 +1 @@ +I love you London \ No newline at end of file diff --git a/Forec/0006/3.txt b/Forec/0006/3.txt new file mode 100644 index 00000000..0b6b47a2 --- /dev/null +++ b/Forec/0006/3.txt @@ -0,0 +1 @@ +I love you changchang \ No newline at end of file diff --git a/Forec/0007/0007.py b/Forec/0007/0007.py new file mode 100644 index 00000000..be31a125 --- /dev/null +++ b/Forec/0007/0007.py @@ -0,0 +1,60 @@ +# coding = utf-8 +# Can detect .py / .c / .cpp +__author__ = 'Forec' +import os +import re + +def get_line( file_path ): + file_dir = os.listdir(file_path) + code ,exp ,space ,alls = ( 0, 0 ,0 , 0) + cFlag = True + exp_re = re.compile(r'[\"\'].*?[\"\']') + for x in file_dir: + if os.path.isfile(x) and ( + os.path.splitext(x)[1] == '.py' + or os.path.splitext(x)[1] == '.c' + or os.path.splitext(x)[1] == '.cpp' + ): + try: + f = open( x, 'r' ) + except: + print('Cannot open file %s' % x) + for line in f.readlines(): + alls += 1 + if line.strip() == '' and cFlag: + space += 1 + continue + find_exp = exp_re.findall(line) + for strs in find_exp: + line = line.replace(strs,'') + if os.path.splitext(x)[1] == '.py': + if '#' in line: + exp += 1 + else : + code += 1 + elif os.path.splitext(x)[1] == '.c' or os.path.splitext(x)[1] == '.cpp': + if r'*/' in line: + cFlag = True + exp += 1 + elif r'/*' in line: + cFlag = False + exp += 1 + elif not cFlag: + exp += 1 + elif r'//' in line: + exp += 1 + else: + code += 1 + cFlag = True + try: + f.close() + except: + pass + + print( '''All Lines total : %d +Codes total : %d +Spaces total: %d +Explanation : %d''' +% ( alls, code, space, exp )) + +get_line('.') diff --git a/Forec/0008/0008.py b/Forec/0008/0008.py new file mode 100644 index 00000000..6bc74a56 --- /dev/null +++ b/Forec/0008/0008.py @@ -0,0 +1,14 @@ +# coding = 'utf-8' +__author__ = 'Forec' + +import requests +from bs4 import BeautifulSoup +import re +import pdb + +# url = input() +url = 'http://forec.github.io/2015/11/01/Computer-Organization-Architecture5/' +html = requests.get(url) + +soup = BeautifulSoup(html.text,"html.parser") +print(soup.body.text.encode('GBK','ignore').decode('GBK')) \ No newline at end of file diff --git a/Forec/0009/0009.py b/Forec/0009/0009.py new file mode 100644 index 00000000..6ae77322 --- /dev/null +++ b/Forec/0009/0009.py @@ -0,0 +1,15 @@ +#coding = utf-8 +# 输入链接 +__author__ = 'Forec' + +import requests +import re +from bs4 import BeautifulSoup + +url = input() +html = requests.get(url) + +soup = BeautifulSoup(html.text,"html.parser") +find_href = soup.findAll('a') +for x in find_href: + print(x['href']) \ No newline at end of file diff --git a/Forec/0010/0010.py b/Forec/0010/0010.py new file mode 100644 index 00000000..52ffda46 --- /dev/null +++ b/Forec/0010/0010.py @@ -0,0 +1,73 @@ +#coding = utf-8 +# Make check codes +__author__ = 'Forec' + +import random +from PIL import Image, ImageDraw, ImageFont, ImageFilter + +num = ''.join(random.sample('abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789',4)) + +def random_col(): + return (random.randint(50,200),random.randint(50,200),random.randint(50,200)) + +def make( strs, width = 400, height = 200): + im = Image.new( 'RGB', (width, height ), (255,255,255)) + draw = ImageDraw.Draw(im) + font = ImageFont.truetype('verdana.ttf',width//4) + font_width , font_height = font.getsize(strs) + strs_len = len(strs) + x = (width - font_width) // 2 + y = (height - font_height ) //2 + total_dex = 0 + for i in strs: + draw.text((x,y), i, random_col(), font) + temp = random.randint(-30,30) + total_dex += temp + im = im.rotate(temp) + draw = ImageDraw.Draw(im) + x += font_width/strs_len + im = im.rotate(-total_dex) + draw = ImageDraw.Draw(im) + draw.line( + [(random.randint(0,width//4), + random.randint(0,height//4) + ), + (random.randint(width//4*3,width), + random.randint(height//4*3,height) + )], + fill = random_col(), + width = width // 80 + ) + draw.line( + [(random.randint(0,width//4), + random.randint(height//4*3,height) + ), + (random.randint(width//3*2,width), + random.randint(0,height//3) + )], + fill = random_col(), + width = width // 80 + ) + draw.line( + [(random.randint(width//4*3,width), + random.randint(height//4*3,height) + ), + (random.randint(width//3*2,width), + random.randint(0,height//3) + )], + fill = random_col(), + width = width // 80 + ) + # im = im.crop((width//10,height//10,width,height)) + for x in range(width): + for y in range(height): + col = im.getpixel((x,y)) + if col == (255,255,255) or col == (0,0,0): + draw.point((x,y), fill = random_col()) + im = im.filter(ImageFilter.BLUR) + # im.show() + # im = im.convert('L') + im.save('out.jpg') + +if __name__ == '__main__': + make(num) \ No newline at end of file diff --git a/Forec/0010/out.jpg b/Forec/0010/out.jpg new file mode 100644 index 00000000..167af1ed Binary files /dev/null and b/Forec/0010/out.jpg differ diff --git a/Forec/0010/verdana.ttf b/Forec/0010/verdana.ttf new file mode 100644 index 00000000..59f22739 Binary files /dev/null and b/Forec/0010/verdana.ttf differ diff --git a/Forec/0011/0011.py b/Forec/0011/0011.py new file mode 100644 index 00000000..b5b1bde7 --- /dev/null +++ b/Forec/0011/0011.py @@ -0,0 +1,15 @@ +# coding = utf-8 +__author__ = 'Forec' +word_filter = set() +with open('filtered_words.txt',"r") as f: + for x in f.readlines(): + word_filter |= {x.rstrip('\n')} +while True: + s = input() + if s == 'exit': + break + elif s in word_filter: + print('Freedom') + else: + print('Human Rights') + \ No newline at end of file diff --git a/Forec/0011/filtered_words.txt b/Forec/0011/filtered_words.txt new file mode 100644 index 00000000..444eb7c6 --- /dev/null +++ b/Forec/0011/filtered_words.txt @@ -0,0 +1,11 @@ + +Ա +Ա +쵼 +ţ +ţ + + +love +sex +jiangge \ No newline at end of file diff --git a/Forec/0012/0012.py b/Forec/0012/0012.py new file mode 100644 index 00000000..5e12a42d --- /dev/null +++ b/Forec/0012/0012.py @@ -0,0 +1,14 @@ +# coding = utf-8 +__author__ = 'Forec' +word_filter = set() +with open('filtered_words.txt',"r") as f: + for x in f.readlines(): + word_filter |= {x.strip('\n')} +while True: + s = input() + if s =='exit': + break + for x in word_filter: + if x in s: + s = s.replace(x,'*'*len(x)) + print(s) \ No newline at end of file diff --git a/Forec/0012/filtered_words.txt b/Forec/0012/filtered_words.txt new file mode 100644 index 00000000..444eb7c6 --- /dev/null +++ b/Forec/0012/filtered_words.txt @@ -0,0 +1,11 @@ + +Ա +Ա +쵼 +ţ +ţ + + +love +sex +jiangge \ No newline at end of file diff --git a/Forec/0013/0013.py b/Forec/0013/0013.py new file mode 100644 index 00000000..71a55dcd --- /dev/null +++ b/Forec/0013/0013.py @@ -0,0 +1,32 @@ +# coding = utf-8 +__author__ = 'Forec' +import urllib, urllib.request +import re + +url = "http://tieba.baidu.com/p/2166231880" +urlhd = urllib.request.Request( url, headers = { + 'Connection': 'Keep-Alive', + 'Accept': 'text/html, application/xhtml+xml, */*', + 'Accept-Language': 'en-US,en;q=0.8,zh-Hans-CN;q=0.5,zh-Hans;q=0.3', + 'User-Agent': 'Mozilla/5.0 (Windows NT 6.3; WOW64; Trident/7.0; rv:11.0) like Gecko' + }) +page = urllib.request.urlopen(urlhd) +try: + data = page.read().decode('utf-8') +except: + exit(0) + +imgre = re.compile(r'src=\"(.*?)\"') +results = imgre.findall(data) +picnum =0 +for x in results: + if '.jpg' not in x: + continue + img = urllib.request.urlopen(x,timeout = 3).read() + try: + f = open(str(picnum)+'.jpg','wb') + f.write(img) + picnum+=1 + f.close; + except: + print('无法将图片%s写入%s' % (x, str(picnum) +'.jpg' ) ) diff --git a/Forec/0014/0014.py b/Forec/0014/0014.py new file mode 100644 index 00000000..d41a39c7 --- /dev/null +++ b/Forec/0014/0014.py @@ -0,0 +1,16 @@ +# coding = utf-8 +__author__ = 'Forec' +import xlwt +import re + +book = xlwt.Workbook(encoding = 'utf-8', style_compression=0) +sheet = book.add_sheet('student',cell_overwrite_ok = True) +line = 0 +info = re.compile(r'\"(\d+)\":\[\"(.*?)\",(\d+),(\d+),(\d+)\]') +with open('student.txt',"r") as f: + data = f.read() +for x in info.findall(data): + for i in range(len(x)): + sheet.write(line,i,x[i]) + line+=1 +book.save('student.xls') \ No newline at end of file diff --git a/Forec/0014/student.txt b/Forec/0014/student.txt new file mode 100644 index 00000000..d3c6eb5b --- /dev/null +++ b/Forec/0014/student.txt @@ -0,0 +1,5 @@ +{ + "1":["",150,120,100], + "2":["",90,99,95], + "3":["",60,66,68] +} \ No newline at end of file diff --git a/Forec/0014/student.xls b/Forec/0014/student.xls new file mode 100644 index 00000000..d8e9262a Binary files /dev/null and b/Forec/0014/student.xls differ diff --git a/Forec/0015/0015.py b/Forec/0015/0015.py new file mode 100644 index 00000000..b2ea1025 --- /dev/null +++ b/Forec/0015/0015.py @@ -0,0 +1,16 @@ +# coding = utf-8 +__author__ = 'Forec' +import xlwt +import re + +book = xlwt.Workbook(encoding = 'utf-8', style_compression=0) +sheet = book.add_sheet('student',cell_overwrite_ok = True) +line = 0 +info = re.compile(r'\"(\d+)\" : \"(.*?)\"') +with open('city.txt',"r") as f: + data = f.read() +for x in info.findall(data): + for i in range(len(x)): + sheet.write(line,i,x[i]) + line+=1 +book.save('city.xls') \ No newline at end of file diff --git a/Forec/0015/city.txt b/Forec/0015/city.txt new file mode 100644 index 00000000..22a2ad33 --- /dev/null +++ b/Forec/0015/city.txt @@ -0,0 +1,5 @@ +{ + "1" : "Ϻ", + "2" : "", + "3" : "ɶ" +} \ No newline at end of file diff --git a/Forec/0015/city.xls b/Forec/0015/city.xls new file mode 100644 index 00000000..55181b4c Binary files /dev/null and b/Forec/0015/city.xls differ diff --git a/Jaccorot/0000/0.jpg b/Jaccorot/0000/0.jpg new file mode 100644 index 00000000..779f5079 Binary files /dev/null and b/Jaccorot/0000/0.jpg differ diff --git a/Jaccorot/0000/0000.py b/Jaccorot/0000/0000.py new file mode 100644 index 00000000..dce1e774 --- /dev/null +++ b/Jaccorot/0000/0000.py @@ -0,0 +1,23 @@ +#!/usr/local/bin/python +#coding=utf-8 + +""" +第 0000 题:将你的 QQ 头像(或者微博头像)右上角加上红色的数字,类似于微信未读信息数量那种提示效果。 类似于图中效果 +""" + +from PIL import Image, ImageDraw, ImageFont + +number = str(5) +color = (255, 0, 0) +windows_font = 'Arial.ttf' + +def draw_text(text, fill_color, windows_font): + im = Image.open('0.jpg') + x, y = im.size + draw = ImageDraw.Draw(im) + font = ImageFont.truetype(windows_font, 35) + draw.text((x-20, 7), text, fill_color, font) + + im.save('1.jpg') + +draw_text(number, color, windows_font) diff --git a/Jaccorot/0000/arial.ttf b/Jaccorot/0000/arial.ttf new file mode 100644 index 00000000..2107596f Binary files /dev/null and b/Jaccorot/0000/arial.ttf differ diff --git a/Jaccorot/0001/0001.py b/Jaccorot/0001/0001.py new file mode 100644 index 00000000..89480858 --- /dev/null +++ b/Jaccorot/0001/0001.py @@ -0,0 +1,22 @@ +#!/usr/local/bin/python +#coding=utf-8 + +#第 0001 题:做为 Apple Store App 独立开发者,你要搞限时促销,为你的应用生成激活码(或者优惠券), +#使用 Python 如何生成 200 个激活码(或者优惠券)? + +import uuid + + +def create_code(num, length): +#生成”num“个激活码,每个激活码含有”length“位 + result = [] + while True: + uuid_id = uuid.uuid1() + temp = str(uuid_id).replace('-', '')[:length] + if not temp in result: + result.append(temp) + if len(result) == num: + break + return result + +print create_code(200, 20) diff --git a/Jaccorot/0002/0002.py b/Jaccorot/0002/0002.py new file mode 100644 index 00000000..5da3a0d8 --- /dev/null +++ b/Jaccorot/0002/0002.py @@ -0,0 +1,41 @@ +#!/usr/local/bin/python +#coding=utf-8 + +#第 0002 题:将 0001 题生成的 200 个激活码(或者优惠券)保存到 MySQL 关系型数据库中。 + +import uuid +import MySQLdb + +def create_code(num, length): +#生成”num“个激活码,每个激活码含有”length“位 + result = [] + while True: + uuid_id = uuid.uuid1() + temp = str(uuid_id).replace('-', '')[:length] + if temp not in result: + result.append(temp) + if len(result) == num: + break + return result + + +def save_to_mysql(num_list): + conn = MySQLdb.connect(host='localhost', user='root', passwd='aaaa', port=3306) + cur = conn.cursor() + + sql_create_database = 'create database if not exists activecode_db' + cur.execute(sql_create_database) + + conn.select_db("activecode_db") + sql_create_table = 'create table if not exists active_codes(active_code char(32))' + cur.execute(sql_create_table) + + cur.executemany('insert into active_codes values(%s)', num_list) + + conn.commit() + cur.close() + conn.close() + +code_num = create_code(200, 20) +#print code_num +save_to_mysql(code_num) diff --git a/Jaccorot/0003/0003.py b/Jaccorot/0003/0003.py new file mode 100644 index 00000000..5c10da40 --- /dev/null +++ b/Jaccorot/0003/0003.py @@ -0,0 +1,27 @@ +#!/usr/local/bin/python +#coding=utf-8 + +#第 0003 题:将 0001 题生成的 200 个激活码(或者优惠券)保存到 Redis 非关系型数据库中。 + +import uuid +import redis + +def create_code(num, length): +#生成”num“个激活码,每个激活码含有”length“位 + result = [] + while True: + uuid_id = uuid.uuid1() + temp = str(uuid_id).replace('-', '')[:length] + if temp not in result: + result.append(temp) + if len(result) == num: + break + return result + + +def save_to_redis(num_list): + r = redis.Redis(host='localhost', port=6379, db=0) + for code in num_list: + r.lpush('code',code) + +save_to_redis(create_code(200,20)) diff --git a/Jaccorot/0004/0004.py b/Jaccorot/0004/0004.py new file mode 100644 index 00000000..f39b1a13 --- /dev/null +++ b/Jaccorot/0004/0004.py @@ -0,0 +1,18 @@ +#!/usr/local/bin/python +#coding=utf-8 + +""" +第 0004 题:任一个英文的纯文本文件,统计其中的单词出现的个数。 +""" +import re + +def count_the_words(path): + with open(path) as f: + text = f.read() + words_list = re.findall(r'[a-zA-Z0-9]+', text) + count = len(words_list) + return count + +if __name__ == '__main__': + nums = count_the_words('file.txt') + print nums \ No newline at end of file diff --git a/Jaccorot/0004/file.txt b/Jaccorot/0004/file.txt new file mode 100644 index 00000000..87d9d7ca --- /dev/null +++ b/Jaccorot/0004/file.txt @@ -0,0 +1,3 @@ +cocococo asdf asdf asdf sdf +sdf +sdf \ No newline at end of file diff --git a/Jaccorot/0005/0.jpg b/Jaccorot/0005/0.jpg new file mode 100644 index 00000000..82d17e99 Binary files /dev/null and b/Jaccorot/0005/0.jpg differ diff --git a/Jaccorot/0005/0005.py b/Jaccorot/0005/0005.py new file mode 100644 index 00000000..cc6bacc4 --- /dev/null +++ b/Jaccorot/0005/0005.py @@ -0,0 +1,37 @@ +#!/usr/local/bin/python +#coding=utf-8 + +""" +第 0005 题:你有一个目录,装了很多照片,把它们的尺寸变成都不大于 iPhone5 分辨率的大小。 +""" +import os +from PIL import Image + +iPhone5_WIDTH = 1136 +iPhone5_HEIGHT = 640 + +def resize_iPhone5_pic(path, new_path, width=iPhone5_WIDTH, height=iPhone5_HEIGHT): + im = Image.open(path) + w,h = im.size + + if w > width: + h = width * h // w + w = width + if h > height: + w = height * w // h + h = height + + im_resized = im.resize((w,h), Image.ANTIALIAS) + im_resized.save(new_path) + + +def walk_dir_and_resize(path): + for root, dirs, files in os.walk(path): + for f_name in files: + if f_name.lower().endswith('jpg'): + path_dst = os.path.join(root,f_name) + f_new_name = 'iPhone5_' + f_name + resize_iPhone5_pic(path=path_dst, new_path=f_new_name) + +if __name__ == '__main__': + walk_dir_and_resize('./') diff --git a/Jaccorot/0006/0006.py b/Jaccorot/0006/0006.py new file mode 100644 index 00000000..4675685c --- /dev/null +++ b/Jaccorot/0006/0006.py @@ -0,0 +1,37 @@ +#!usr/bin/python +#coding=utf-8 + +""" +第 0006 题:你有一个目录,放了你一个月的日记,都是 txt,为了避免分词的问题, +假设内容都是英文,请统计出你认为每篇日记最重要的词。 +""" + +import os +import re + +def walk_dir(path): + file_path = [] + for root, dirs, files in os.walk(path): + for f in files: + if f.lower().endswith('txt'): + file_path.append(os.path.join(root, f)) + return file_path + +def find_key_word(filepath): + word_dic = {} + filename = os.path.basename(filepath) + with open(filepath) as f: + text = f.read() + words_list = re.findall(r'[A-Za-z]+', text.lower()) + for w in words_list: + if w in word_dic: + word_dic[w] += 1 + else: + word_dic[w] = 1 + sorted_word_list = sorted(word_dic.items(), key=lambda d: d[1]) + print u"在%s文件中,%s为关键词,共出现了%s次" %(filename, sorted_word_list[-1][0], sorted_word_list[-1][1]) + +if __name__ == "__main__": + for file_path in walk_dir(os.getcwd()): + find_key_word(file_path) + diff --git a/Jaccorot/0006/1.txt b/Jaccorot/0006/1.txt new file mode 100644 index 00000000..cc7f0cfd --- /dev/null +++ b/Jaccorot/0006/1.txt @@ -0,0 +1 @@ +a b c d a a d \ No newline at end of file diff --git a/Jaccorot/0006/2.txt b/Jaccorot/0006/2.txt new file mode 100644 index 00000000..c07c71c2 --- /dev/null +++ b/Jaccorot/0006/2.txt @@ -0,0 +1 @@ +a b c d a a d d b d d x zx fd fd fd fd fd fd fd fd fd FD FD FD FD D FD FD FD FD fD FD FD FD \ No newline at end of file diff --git a/Jaccorot/0007/0007.py b/Jaccorot/0007/0007.py new file mode 100644 index 00000000..15daf5d9 --- /dev/null +++ b/Jaccorot/0007/0007.py @@ -0,0 +1,48 @@ +#!/usr/bin/python +#coding:utf-8 + +""" +第 0007 题:有个目录,里面是你自己写过的程序,统计一下你写过多少行代码。包括空行和注释,但是要分别列出来。 +""" + +import os + +def walk_dir(path): + file_path = [] + for root, dirs, files in os.walk(path): + for f in files: + if f.lower().endswith('py'): + file_path.append(os.path.join(root, f)) + return file_path + + +def count_the_code(path): + file_name = os.path.basename(path) + note_flag = False + line_num = 0 + empty_line_num = 0 + note_num = 0 + with open(path) as f: + for line in f.read().split('\n'): + line_num += 1 + if line.strip().startswith('\"\"\"') and not note_flag: + note_flag =True + note_num += 1 + continue + + if line.strip().startswith('\"\"\"'): + note_flag = False + note_num += 1 + + if line.strip().startswith('#') or note_flag: + note_num += 1 + + if len(line) == 0: + empty_line_num += 1 + + print u"在%s中,共有%s行代码,其中有%s空行,有%s注释"% (file_name, line_num, empty_line_num, note_num) + + +if __name__ == '__main__': + for f in walk_dir('.'): + count_the_code(f) diff --git a/Jaccorot/0008/0008.py b/Jaccorot/0008/0008.py new file mode 100644 index 00000000..9dd5f8d4 --- /dev/null +++ b/Jaccorot/0008/0008.py @@ -0,0 +1,19 @@ +#!/usr/bin/python +#coding=utf-8 + +""" +第 0008 题:一个HTML文件,找出里面的正文。 +""" + +from bs4 import BeautifulSoup + +def find_the_content(path): + with open(path) as f: + text = BeautifulSoup(f, 'lxml') + content = text.get_text().strip('\n') + + return content.encode('gbk','ignore') + + +if __name__ == '__main__': + print find_the_content('Show-Me-the-Code_show-me-the-code_1.html') diff --git a/Jaccorot/0008/Show-Me-the-Code_show-me-the-code_1.html b/Jaccorot/0008/Show-Me-the-Code_show-me-the-code_1.html new file mode 100644 index 00000000..e9238840 --- /dev/null +++ b/Jaccorot/0008/Show-Me-the-Code_show-me-the-code_1.html @@ -0,0 +1,974 @@ + + + + + + + + + + Show-Me-the-Code/show-me-the-code + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Skip to content + + + + + + + + + + + + + + +
+ +
+
+ + +
+
+
+ +
+ +
+ + +
    + +
  • +
    + +
    + + + + Watch + + + + +
    + +
    +
    +
    +
  • + +
  • + +
    + +
    + + +
    +
    + + +
    + +
  • + +
  • + + + Fork + + + + + +
  • +
+ +

+ + /show-me-the-code + + + + + + + forked from Yixiaohan/show-me-the-code + +

+ +
+
+
+ +
+
+
+ + + +
+ +
+

HTTPS clone URL

+
+ + + + +
+
+ + +
+

SSH clone URL

+
+ + + + +
+
+ + +
+

Subversion checkout URL

+
+ + + + +
+
+ + + +
You can clone with +
,
, or
. + + + +
+ + + Clone in Desktop + + + + + Download ZIP + +
+
+
+ + + + +
+
+ Python 练习册,每天一个小程序 +
+ + +
+ + + + + +
+ +
+ + +
+ + + + + + + + +
+ + Branch: + master + + + +
+ + + +
+ + + +
+ + + + Pull request + + + + Compare + + + + This branch is 5 commits ahead, 3 commits behind Yixiaohan:master. +
+ + +
+

+ update format & add guide + +

+
+ + latest commit 16e0949bb7 + +
+ @horx + horx + authored + +
+
+
+ + +
+ + + + + + + + + + + + + + + + + + +
Failed to load latest commit information.
+ +
+ + +
+

+ + README.md +

+ +

Python 练习册,每天一个小程序

+ +

说明:

+ +
    +
  • Python 练习册,每天一个小程序。注:将 Python 换成其他语言,大多数题目也适用
  • +
  • 不会出现诸如「打印九九乘法表」、「打印水仙花」之类的题目
  • +
  • 本文本文由@史江歌(shijiangge@gmail.com QQ:499065469)根据互联网资料收集整理而成,感谢互联网,感谢各位的分享。鸣谢!本文会不断更新。
  • +
  • 欢迎大家 Pull Request 出题目,贴代码(Gist、Blog皆可):-)
  • +
  • 欢迎解答, 并发送 pull request 到 Show-Me-the-Code
  • +
+ +
+

Talk is cheap. Show me the code.--Linus Torvalds

+
+ +
+ +

第 0000 题:将你的 QQ 头像(或者微博头像)右上角加上红色的数字,类似于微信未读信息数量那种提示效果。 +类似于图中效果

+ +

头像

+ +

第 0001 题:做为 Apple Store App 独立开发者,你要搞限时促销,为你的应用生成激活码(或者优惠券),使用 Python 如何生成 200 个激活码(或者优惠券)?

+ +

第 0002 题:将 0001 题生成的 200 个激活码(或者优惠券)保存到 MySQL 关系型数据库中。

+ +

第 0003 题:将 0001 题生成的 200 个激活码(或者优惠券)保存到 Redis 非关系型数据库中。

+ +

第 0004 题:任一个英文的纯文本文件,统计其中的单词出现的个数。

+ +

第 0005 题:你有一个目录,装了很多照片,把它们的尺寸变成都不大于 iPhone5 分辨率的大小。

+ +

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

+ +

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

+ +

第 0008 题:一个HTML文件,找出里面的正文

+ +

第 0009 题:一个HTML文件,找出里面的链接

+ +

第 0010 题:使用 Python 生成类似于下图中的字母验证码图片

+ +

字母验证码

+ + + +

第 0011 题: 敏感词文本文件 filtered_words.txt,里面的内容为以下内容,当用户输入敏感词语时,则打印出 Freedom,否则打印出 Human Rights。

+ +
北京
+程序员
+公务员
+领导
+牛比
+牛逼
+你娘
+你妈
+love
+sex
+jiangge
+
+ +

第 0012 题: 敏感词文本文件 filtered_words.txt,里面的内容 和 0011题一样,当用户输入敏感词语,则用 星号 * 替换,例如当用户输入「北京是个好城市」,则变成「**是个好城市」。

+ +

第 0013 题: 用 Python 写一个爬图片的程序,爬 这个链接里的日本妹子图片 :-)

+ + + +

第 0014 题: 纯文本文件 student.txt为学生信息, 里面的内容(包括花括号)如下所示:

+ +
{
+    "1":["张三",150,120,100],
+    "2":["李四",90,99,95],
+    "3":["王五",60,66,68]
+}
+
+ +

请将上述内容写到 student.xls 文件中,如下图所示:

+ +

student.xls

+ +
    +
  • 阅读资料 腾讯游戏开发 XML 和 Excel 内容相互转换
  • +
+ +

第 0015 题: 纯文本文件 city.txt为城市信息, 里面的内容(包括花括号)如下所示:

+ +
{
+    "1" : "上海",
+    "2" : "北京",
+    "3" : "成都"
+}
+
+ +

请将上述内容写到 city.xls 文件中,如下图所示:

+ +

city.xls

+ +

第 0016 题: 纯文本文件 numbers.txt, 里面的内容(包括方括号)如下所示:

+ +
[
+    [1, 82, 65535],
+    [20, 90, 13],
+    [26, 809, 1024]
+]
+
+ +

请将上述内容写到 numbers.xls 文件中,如下图所示:

+ +

numbers.xls

+ +

第 0017 题: 将 第 0014 题中的 student.xls 文件中的内容写到 student.xml 文件中,如

+ +

下所示:

+ +
<?xml version="1.0" encoding="UTF-8"?>
+<root>
+<students>
+<!--
+    学生信息表
+    "id" : [名字, 数学, 语文, 英文]
+-->
+{
+    "1" : ["张三", 150, 120, 100],
+    "2" : ["李四", 90, 99, 95],
+    "3" : ["王五", 60, 66, 68]
+}
+</students>
+</root>
+
+ +
    +
  • 阅读资料 腾讯游戏开发 xml 和 Excel 相互转换
  • +
+ +

第 0018 题: 将 第 0015 题中的 city.xls 文件中的内容写到 city.xml 文件中,如下所示:

+ +
<?xmlversion="1.0" encoding="UTF-8"?>
+<root>
+<citys>
+<!--
+    城市信息
+-->
+{
+    "1" : "上海",
+    "2" : "北京",
+    "3" : "成都"
+}
+</citys>
+</root>
+
+ +

第 0019 题: 将 第 0016 题中的 numbers.xls 文件中的内容写到 numbers.xml 文件中,如下

+ +

所示:

+ +
<?xml version="1.0" encoding="UTF-8"?>
+<root>
+<numbers>
+<!--
+    数字信息
+-->
+
+[
+    [1, 82, 65535],
+    [20, 90, 13],
+    [26, 809, 1024]
+]
+
+</numbers>
+</root>
+
+ +

第 0020 题: 登陆中国联通网上营业厅 后选择「自助服务」 --> 「详单查询」,然后选择你要查询的时间段,点击「查询」按钮,查询结果页面的最下方,点击「导出」,就会生成类似于 2014年10月01日~2014年10月31日通话详单.xls 文件。写代码,对每月通话时间做个统计。

+ +

第 0021 题: 通常,登陆某个网站或者 APP,需要使用用户名和密码。密码是如何加密后存储起来的呢?请使用 Python 对密码加密。

+ + + +

第 0022 题: iPhone 6、iPhone 6 Plus 早已上市开卖。请查看你写得 第 0005 题的代码是否可以复用。

+ +

第 0023 题: 使用 Python 的 Web 框架,做一个 Web 版本 留言簿 应用。

+ +

阅读资料:Python 有哪些 Web 框架

+ +
    +
  • 留言簿参考
  • +
+ +

第 0024 题: 使用 Python 的 Web 框架,做一个 Web 版本 TodoList 应用。

+ +
    +
  • SpringSide 版TodoList
  • +
+ +

第 0025 题: 使用 Python 实现:对着电脑吼一声,自动打开浏览器中的默认网站。

+ +
例如,对着笔记本电脑吼一声“百度”,浏览器自动打开百度首页。
+
+关键字:Speech to Text
+
+ +

参考思路: +1:获取电脑录音-->WAV文件 + python record wav

+ +

2:录音文件-->文本

+ +
STT: Speech to Text
+
+STT API Google API
+
+ +

3:文本-->电脑命令

+
+
+ + +
+
+ +
+
+ + +
+ +
+ +
+ + + + + + + +
+ + + Something went wrong with that request. Please try again. +
+ + + + + + + + + + + \ No newline at end of file diff --git a/Jaccorot/0009/0009.py b/Jaccorot/0009/0009.py new file mode 100644 index 00000000..65a70b0c --- /dev/null +++ b/Jaccorot/0009/0009.py @@ -0,0 +1,22 @@ +#!/usr/bin/python +#coding=utf-8 + +""" + +第 0009 题:一个HTML文件,找出里面的链接 + +""" + +from bs4 import BeautifulSoup + +def find_the_link(filepath): + links = [] + with open(filepath) as f: + text = f.read() + bs =BeautifulSoup(text) + for i in bs.find_all('a'): + links.append(i['href']) + return links + +if __name__ == '__main__': + print find_the_link('Show-Me-the-Code_show-me-the-code_1.html') \ No newline at end of file diff --git a/Jaccorot/0009/Show-Me-the-Code_show-me-the-code_1.html b/Jaccorot/0009/Show-Me-the-Code_show-me-the-code_1.html new file mode 100644 index 00000000..e9238840 --- /dev/null +++ b/Jaccorot/0009/Show-Me-the-Code_show-me-the-code_1.html @@ -0,0 +1,974 @@ + + + + + + + + + + Show-Me-the-Code/show-me-the-code + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Skip to content + + + + + + + + + + + + + + +
+ +
+
+ + +
+
+
+ +
+ +
+ + +
    + +
  • +
    + +
    + + + + Watch + + + + +
    + +
    +
    +
    +
  • + +
  • + +
    + +
    + + +
    +
    + + +
    + +
  • + +
  • + + + Fork + + + + + +
  • +
+ +

+ + /show-me-the-code + + + + + + + forked from Yixiaohan/show-me-the-code + +

+ +
+
+
+ +
+
+
+ + + +
+ +
+

HTTPS clone URL

+
+ + + + +
+
+ + +
+

SSH clone URL

+
+ + + + +
+
+ + +
+

Subversion checkout URL

+
+ + + + +
+
+ + + +
You can clone with +
,
, or
. + + + +
+ + + Clone in Desktop + + + + + Download ZIP + +
+
+
+ + + + +
+
+ Python 练习册,每天一个小程序 +
+ + +
+ + + + + +
+ +
+ + +
+ + + + + + + + +
+ + Branch: + master + + + +
+ + + +
+ + + +
+ + + + Pull request + + + + Compare + + + + This branch is 5 commits ahead, 3 commits behind Yixiaohan:master. +
+ + +
+

+ update format & add guide + +

+
+ + latest commit 16e0949bb7 + +
+ @horx + horx + authored + +
+
+
+ + +
+ + + + + + + + + + + + + + + + + + +
Failed to load latest commit information.
+ +
+ + +
+

+ + README.md +

+ +

Python 练习册,每天一个小程序

+ +

说明:

+ +
    +
  • Python 练习册,每天一个小程序。注:将 Python 换成其他语言,大多数题目也适用
  • +
  • 不会出现诸如「打印九九乘法表」、「打印水仙花」之类的题目
  • +
  • 本文本文由@史江歌(shijiangge@gmail.com QQ:499065469)根据互联网资料收集整理而成,感谢互联网,感谢各位的分享。鸣谢!本文会不断更新。
  • +
  • 欢迎大家 Pull Request 出题目,贴代码(Gist、Blog皆可):-)
  • +
  • 欢迎解答, 并发送 pull request 到 Show-Me-the-Code
  • +
+ +
+

Talk is cheap. Show me the code.--Linus Torvalds

+
+ +
+ +

第 0000 题:将你的 QQ 头像(或者微博头像)右上角加上红色的数字,类似于微信未读信息数量那种提示效果。 +类似于图中效果

+ +

头像

+ +

第 0001 题:做为 Apple Store App 独立开发者,你要搞限时促销,为你的应用生成激活码(或者优惠券),使用 Python 如何生成 200 个激活码(或者优惠券)?

+ +

第 0002 题:将 0001 题生成的 200 个激活码(或者优惠券)保存到 MySQL 关系型数据库中。

+ +

第 0003 题:将 0001 题生成的 200 个激活码(或者优惠券)保存到 Redis 非关系型数据库中。

+ +

第 0004 题:任一个英文的纯文本文件,统计其中的单词出现的个数。

+ +

第 0005 题:你有一个目录,装了很多照片,把它们的尺寸变成都不大于 iPhone5 分辨率的大小。

+ +

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

+ +

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

+ +

第 0008 题:一个HTML文件,找出里面的正文

+ +

第 0009 题:一个HTML文件,找出里面的链接

+ +

第 0010 题:使用 Python 生成类似于下图中的字母验证码图片

+ +

字母验证码

+ + + +

第 0011 题: 敏感词文本文件 filtered_words.txt,里面的内容为以下内容,当用户输入敏感词语时,则打印出 Freedom,否则打印出 Human Rights。

+ +
北京
+程序员
+公务员
+领导
+牛比
+牛逼
+你娘
+你妈
+love
+sex
+jiangge
+
+ +

第 0012 题: 敏感词文本文件 filtered_words.txt,里面的内容 和 0011题一样,当用户输入敏感词语,则用 星号 * 替换,例如当用户输入「北京是个好城市」,则变成「**是个好城市」。

+ +

第 0013 题: 用 Python 写一个爬图片的程序,爬 这个链接里的日本妹子图片 :-)

+ + + +

第 0014 题: 纯文本文件 student.txt为学生信息, 里面的内容(包括花括号)如下所示:

+ +
{
+    "1":["张三",150,120,100],
+    "2":["李四",90,99,95],
+    "3":["王五",60,66,68]
+}
+
+ +

请将上述内容写到 student.xls 文件中,如下图所示:

+ +

student.xls

+ +
    +
  • 阅读资料 腾讯游戏开发 XML 和 Excel 内容相互转换
  • +
+ +

第 0015 题: 纯文本文件 city.txt为城市信息, 里面的内容(包括花括号)如下所示:

+ +
{
+    "1" : "上海",
+    "2" : "北京",
+    "3" : "成都"
+}
+
+ +

请将上述内容写到 city.xls 文件中,如下图所示:

+ +

city.xls

+ +

第 0016 题: 纯文本文件 numbers.txt, 里面的内容(包括方括号)如下所示:

+ +
[
+    [1, 82, 65535],
+    [20, 90, 13],
+    [26, 809, 1024]
+]
+
+ +

请将上述内容写到 numbers.xls 文件中,如下图所示:

+ +

numbers.xls

+ +

第 0017 题: 将 第 0014 题中的 student.xls 文件中的内容写到 student.xml 文件中,如

+ +

下所示:

+ +
<?xml version="1.0" encoding="UTF-8"?>
+<root>
+<students>
+<!--
+    学生信息表
+    "id" : [名字, 数学, 语文, 英文]
+-->
+{
+    "1" : ["张三", 150, 120, 100],
+    "2" : ["李四", 90, 99, 95],
+    "3" : ["王五", 60, 66, 68]
+}
+</students>
+</root>
+
+ +
    +
  • 阅读资料 腾讯游戏开发 xml 和 Excel 相互转换
  • +
+ +

第 0018 题: 将 第 0015 题中的 city.xls 文件中的内容写到 city.xml 文件中,如下所示:

+ +
<?xmlversion="1.0" encoding="UTF-8"?>
+<root>
+<citys>
+<!--
+    城市信息
+-->
+{
+    "1" : "上海",
+    "2" : "北京",
+    "3" : "成都"
+}
+</citys>
+</root>
+
+ +

第 0019 题: 将 第 0016 题中的 numbers.xls 文件中的内容写到 numbers.xml 文件中,如下

+ +

所示:

+ +
<?xml version="1.0" encoding="UTF-8"?>
+<root>
+<numbers>
+<!--
+    数字信息
+-->
+
+[
+    [1, 82, 65535],
+    [20, 90, 13],
+    [26, 809, 1024]
+]
+
+</numbers>
+</root>
+
+ +

第 0020 题: 登陆中国联通网上营业厅 后选择「自助服务」 --> 「详单查询」,然后选择你要查询的时间段,点击「查询」按钮,查询结果页面的最下方,点击「导出」,就会生成类似于 2014年10月01日~2014年10月31日通话详单.xls 文件。写代码,对每月通话时间做个统计。

+ +

第 0021 题: 通常,登陆某个网站或者 APP,需要使用用户名和密码。密码是如何加密后存储起来的呢?请使用 Python 对密码加密。

+ + + +

第 0022 题: iPhone 6、iPhone 6 Plus 早已上市开卖。请查看你写得 第 0005 题的代码是否可以复用。

+ +

第 0023 题: 使用 Python 的 Web 框架,做一个 Web 版本 留言簿 应用。

+ +

阅读资料:Python 有哪些 Web 框架

+ +
    +
  • 留言簿参考
  • +
+ +

第 0024 题: 使用 Python 的 Web 框架,做一个 Web 版本 TodoList 应用。

+ +
    +
  • SpringSide 版TodoList
  • +
+ +

第 0025 题: 使用 Python 实现:对着电脑吼一声,自动打开浏览器中的默认网站。

+ +
例如,对着笔记本电脑吼一声“百度”,浏览器自动打开百度首页。
+
+关键字:Speech to Text
+
+ +

参考思路: +1:获取电脑录音-->WAV文件 + python record wav

+ +

2:录音文件-->文本

+ +
STT: Speech to Text
+
+STT API Google API
+
+ +

3:文本-->电脑命令

+
+
+ + +
+
+ +
+
+ + +
+ +
+ +
+ + + + + + + +
+ + + Something went wrong with that request. Please try again. +
+ + + + + + + + + + + \ No newline at end of file diff --git a/Jaccorot/0010/0010.py b/Jaccorot/0010/0010.py new file mode 100644 index 00000000..21b9a422 --- /dev/null +++ b/Jaccorot/0010/0010.py @@ -0,0 +1,48 @@ +#!/usr/bin/python +#coding=utf-8 + +""" + +第 0010 题:使用 Python 生成字母验证码图片 + +""" + +from PIL import Image, ImageDraw, ImageFont, ImageFilter +import random + +IMAGE_MODE = 'RGB' +IMAGE_BG_COLOR = (255,255,255) +Image_Font = 'arial.ttf' +text = ''.join(random.sample('abcdefghijklmnopqrstuvwxyz\ +ABCDEFGHIJKLMNOPQRSTUVWXYZ',4)) + +def colorRandom(): + return (random.randint(32,127),random.randint(32,127),random.randint(32,127)) + + +#change 噪点频率(%) +def create_identifying_code(strs, width=400, height=200, chance=2): + im = Image.new(IMAGE_MODE, (width, height), IMAGE_BG_COLOR) + draw = ImageDraw.Draw(im) + #绘制背景噪点 + for w in xrange(width): + for h in xrange(height): + if chance < random.randint(1, 100): + draw.point((w, h), fill=colorRandom()) + + font = ImageFont.truetype(Image_Font, 80) + font_width, font_height = font.getsize(strs) + strs_len = len(strs) + x = (width - font_width)/2 + y = (height - font_height)/2 + #逐个绘制文字 + for i in strs: + draw.text((x,y), i, colorRandom(), font) + x += font_width/strs_len + #模糊 + im = im.filter(ImageFilter.BLUR) + im.save('identifying_code_pic.jpg') + + +if __name__ == '__main__': + create_identifying_code(text) diff --git a/Jaccorot/0010/arial.ttf b/Jaccorot/0010/arial.ttf new file mode 100644 index 00000000..2107596f Binary files /dev/null and b/Jaccorot/0010/arial.ttf differ diff --git a/Jaccorot/0010/identifying_code_pic.jpg b/Jaccorot/0010/identifying_code_pic.jpg new file mode 100644 index 00000000..61a33564 Binary files /dev/null and b/Jaccorot/0010/identifying_code_pic.jpg differ diff --git a/Jaccorot/0011/0011.py b/Jaccorot/0011/0011.py new file mode 100644 index 00000000..0d9d3bca --- /dev/null +++ b/Jaccorot/0011/0011.py @@ -0,0 +1,28 @@ +#!/usr/bin/python +# coding=utf-8 + +""" +第 0011 题: 敏感词文本文件 filtered_words.txt,里面的内容为以下内容,当用户输入敏感词语时,则打印出 Freedom, +否则打印出 Human Rights。 +""" + + +def trans_to_words(): + type_in = raw_input(">") + judge_flag = False + with open('filtered_words.txt') as f: + text = f.read().decode('utf-8').encode('gbk') + + for i in text.split("\n"): + if i in type_in: + judge_flag = True + + if judge_flag: + print "Freedom" + else: + print "Human Rights" + + +if __name__ == "__main__": + while True: + trans_to_words() diff --git a/Jaccorot/0011/filtered_words.txt b/Jaccorot/0011/filtered_words.txt new file mode 100644 index 00000000..69373b64 --- /dev/null +++ b/Jaccorot/0011/filtered_words.txt @@ -0,0 +1,11 @@ +北京 +程序员 +公务员 +领导 +牛比 +牛逼 +你娘 +你妈 +love +sex +jiangge \ No newline at end of file diff --git a/Jaccorot/0012/0012.py b/Jaccorot/0012/0012.py new file mode 100644 index 00000000..dae4d5e9 --- /dev/null +++ b/Jaccorot/0012/0012.py @@ -0,0 +1,22 @@ +#!/usr/bin/python +# coding=utf-8 + +""" +第 0012 题: 敏感词文本文件 filtered_words.txt,里面的内容 和 0011题一样, +当用户输入敏感词语,则用 星号 * 替换,例如当用户输入「北京是个好城市」,则变成「**是个好城市」。 +""" + + +def trans_to_words(): + type_in = raw_input(">") + with open('filtered_words.txt') as f: + text = f.read().decode('utf-8').encode('gbk') + print text.split("\n") + for i in text.split("\n"): + if i in type_in: + type_in = type_in.replace(i, '**') + print type_in + +if __name__ == "__main__": + while True: + trans_to_words() diff --git a/Jaccorot/0012/filtered_words.txt b/Jaccorot/0012/filtered_words.txt new file mode 100644 index 00000000..69373b64 --- /dev/null +++ b/Jaccorot/0012/filtered_words.txt @@ -0,0 +1,11 @@ +北京 +程序员 +公务员 +领导 +牛比 +牛逼 +你娘 +你妈 +love +sex +jiangge \ No newline at end of file diff --git a/Jaccorot/0013/0013.py b/Jaccorot/0013/0013.py new file mode 100644 index 00000000..ad340a09 --- /dev/null +++ b/Jaccorot/0013/0013.py @@ -0,0 +1,30 @@ +#!/usr/bin/python +# coding=utf-8 + +""" +第 0013 题: 用 Python 写一个爬图片的程序,爬 这个链接里的日本妹子图片 :-) +""" + +import os +import urllib +from bs4 import BeautifulSoup +from urlparse import urlsplit + + +def catch_tieba_pics(url): + content = urllib.urlopen(url) + bs = BeautifulSoup(content, 'lxml') + for i in bs.find_all('img', {"class": "BDE_Image"}): + download_pic(i['src']) + + +def download_pic(url): + image_content = urllib.urlopen(url).read() + file_name = os.path.basename(urlsplit(url)[2]) + output = open(file_name, 'wb') + output.write(image_content) + output.close() + + +if __name__ == '__main__': + catch_tieba_pics('http://tieba.baidu.com/p/2166231880') diff --git a/Jaccorot/0014/0014.py b/Jaccorot/0014/0014.py new file mode 100644 index 00000000..5eaa5b05 --- /dev/null +++ b/Jaccorot/0014/0014.py @@ -0,0 +1,42 @@ +#!/usr/bin/python +# coding=utf-8 + +""" +第 0014 题: 纯文本文件 student.txt为学生信息, 里面的内容(包括花括号)如下所示, +请将上述内容写到 student.xls 文件中,如下图所示: +""" + +import os +import json +import xlwt + +def read_txt(path): + with open(path, 'r') as f: + text = f.read().decode('utf-8') + text_json = json.loads(text) + return text_json + + +def save_into_excel(content_dict, excel_name): + wb = xlwt.Workbook() + ws = wb.add_sheet("student", cell_overwrite_ok=True) + row = 0 + col = 0 + + for k, v in sorted(content_dict.items(),key=lambda d:d[0]): + ws.write(row, col, k) + for i in v: + col += 1 + ws.write(row, col, i) + + row += 1 + col = 0 + + wb.save(excel_name) + + +if __name__ == "__main__": + read_content = read_txt(os.path.join(os.path.split(__file__)[0], 'student.txt')) + save_into_excel(read_content, 'student.xls') + + diff --git a/JiYouMCC/0014/student.txt b/Jaccorot/0014/student.txt similarity index 100% rename from JiYouMCC/0014/student.txt rename to Jaccorot/0014/student.txt diff --git a/Jaccorot/0015/0015.py b/Jaccorot/0015/0015.py new file mode 100644 index 00000000..113927c3 --- /dev/null +++ b/Jaccorot/0015/0015.py @@ -0,0 +1,39 @@ +#!/usr/bin/python +# coding=utf-8 + +""" +纯文本文件 city.txt为城市信息, 里面的内容(包括花括号)如下所示: +请将上述内容写到 city.xls 文件中,如下图所示: +""" + +import os +import json +import xlwt + +def read_txt(path): + with open(path, 'r') as f: + text = f.read().decode('utf-8') + text_json = json.loads(text) + return text_json + + +def save_into_excel(content_dict, excel_name): + wb = xlwt.Workbook() + ws = wb.add_sheet("city", cell_overwrite_ok=True) + row = 0 + col = 0 + + for k, v in sorted(content_dict.items(),key=lambda d:d[0]): + ws.write(row, col, k) + col += 1 + ws.write(row, col, v) + + row += 1 + col = 0 + + wb.save(excel_name) + + +if __name__ == "__main__": + read_content = read_txt(os.path.join(os.path.split(__file__)[0], 'city.txt')) + save_into_excel(read_content, 'city.xls') diff --git a/JiYouMCC/0015/city.txt b/Jaccorot/0015/city.txt similarity index 100% rename from JiYouMCC/0015/city.txt rename to Jaccorot/0015/city.txt diff --git a/Jaccorot/0016/0016.py b/Jaccorot/0016/0016.py new file mode 100644 index 00000000..c0fe6620 --- /dev/null +++ b/Jaccorot/0016/0016.py @@ -0,0 +1,37 @@ +#!/usr/bin/python +# coding=utf-8 + +""" + 纯文本文件 numbers.txt, 里面的内容(包括方括号)如下所示: +请将上述内容写到 numbers.xls 文件中,如下图所示: +""" + +import os +import json +import xlwt + +def read_txt(path): + with open(path, 'r') as f: + text = f.read().decode('utf-8') + text_json = json.loads(text) + return text_json + + +def save_into_excel(content_dict, excel_name): + wb = xlwt.Workbook() + ws = wb.add_sheet("numbers", cell_overwrite_ok=True) + row = 0 + col = 0 + for i in content_dict: + for k in i: + ws.write(row, col, k) + col += 1 + row += 1 + col = 0 + + wb.save(excel_name) + + +if __name__ == "__main__": + read_content = read_txt(os.path.join(os.path.split(__file__)[0], 'numbers.txt')) + save_into_excel(read_content, 'numbers.xls') diff --git a/JiYouMCC/0016/numbers.txt b/Jaccorot/0016/numbers.txt similarity index 100% rename from JiYouMCC/0016/numbers.txt rename to Jaccorot/0016/numbers.txt diff --git a/Jaccorot/0017/0017.py b/Jaccorot/0017/0017.py new file mode 100644 index 00000000..335c94bc --- /dev/null +++ b/Jaccorot/0017/0017.py @@ -0,0 +1,50 @@ +#!/usr/bin/python +# coding=utf-8 + +""" +第 0017 题: 将 第 0014 题中的 student.xls 文件中的内容写到 student.xml 文件中,如 + +下所示: + + + + + +{ + "1" : ["张三", 150, 120, 100], + "2" : ["李四", 90, 99, 95], + "3" : ["王五", 60, 66, 68] +} + + +""" + +import xlrd +import json +from lxml import etree + + +def read_exl(file_name): + exl = xlrd.open_workbook(file_name) + exl_sheet = exl.sheet_by_name('student') + data = {} + for i in range(exl_sheet.nrows): + data[exl_sheet.row_values(i)[0]] = exl_sheet.row_values(i)[1:] + return json.dumps(data, encoding='utf-8') + +def save_to_xml(data, new_file_name): + root = etree.Element('root') + students = etree.SubElement(root, 'students') + students.append(etree.Comment(u"""学生信息表 "id" : [名字, 数学, 语文, 英文]""")) + students.text = data + + student_xml = etree.ElementTree(root) + student_xml.write(new_file_name, pretty_print=True, xml_declaration=True, encoding='utf-8') + + +if __name__ == '__main__': + content = read_exl('student.xls') + save_to_xml(content, 'student.xml') diff --git a/Jaccorot/0017/student.xls b/Jaccorot/0017/student.xls new file mode 100644 index 00000000..7d5717d8 Binary files /dev/null and b/Jaccorot/0017/student.xls differ diff --git a/Jaccorot/0017/student.xml b/Jaccorot/0017/student.xml new file mode 100644 index 00000000..afc2e49e --- /dev/null +++ b/Jaccorot/0017/student.xml @@ -0,0 +1,4 @@ + + + {"1": ["\u5f20\u4e09", 150.0, 120.0, 100.0], "3": ["\u738b\u4e94", 60.0, 66.0, 68.0], "2": ["\u674e\u56db", 90.0, 99.0, 95.0]} + diff --git a/Jaccorot/0018/0018.py b/Jaccorot/0018/0018.py new file mode 100644 index 00000000..bbdaddd2 --- /dev/null +++ b/Jaccorot/0018/0018.py @@ -0,0 +1,47 @@ +#!/usr/bin/python +# coding=utf-8 + +""" +第 0018 题: 将 第 0015 题中的 city.xls 文件中的内容写到 city.xml 文件中,如下所示: + + + + + +{ + "1" : "上海", + "2" : "北京", + "3" : "成都" +} + + +""" + +import xlrd +import json +from lxml import etree + + +def read_exl(file_name): + exl = xlrd.open_workbook(file_name) + exl_sheet = exl.sheet_by_name('city') + data = {} + for i in range(exl_sheet.nrows): + data[exl_sheet.row_values(i)[0]] = exl_sheet.row_values(i)[1] + return json.dumps(data, encoding='utf-8') + +def save_to_xml(data, new_file_name): + root = etree.Element('root') + students = etree.SubElement(root, 'citys') + students.append(etree.Comment(u"""城市信息""")) + students.text = data + + student_xml = etree.ElementTree(root) + student_xml.write(new_file_name, pretty_print=True, xml_declaration=True, encoding='utf-8') + + +if __name__ == '__main__': + content = read_exl('city.xls') + save_to_xml(content, 'city.xml') diff --git a/Jaccorot/0018/city.xls b/Jaccorot/0018/city.xls new file mode 100644 index 00000000..ef48fed2 Binary files /dev/null and b/Jaccorot/0018/city.xls differ diff --git a/Jaccorot/0018/city.xml b/Jaccorot/0018/city.xml new file mode 100644 index 00000000..14186a8c --- /dev/null +++ b/Jaccorot/0018/city.xml @@ -0,0 +1,4 @@ + + + {"1": "\u4e0a\u6d77", "3": "\u6210\u90fd", "2": "\u5317\u4eac"} + diff --git a/Jaccorot/0019/0019.py b/Jaccorot/0019/0019.py new file mode 100644 index 00000000..4112b3ad --- /dev/null +++ b/Jaccorot/0019/0019.py @@ -0,0 +1,52 @@ +#!/usr/bin/python +# coding=utf-8 + +""" +第 0019 题: 将 第 0016 题中的 numbers.xls 文件中的内容写到 numbers.xml 文件中,如下 + +所示: + + + + + + +[ + [1, 82, 65535], + [20, 90, 13], + [26, 809, 1024] +] + + + +""" + +import xlrd +import json +from lxml import etree + + +def read_exl(file_name): + exl = xlrd.open_workbook(file_name) + exl_sheet = exl.sheet_by_name('numbers') + data = [] + for i in range(exl_sheet.nrows): + temp = [int(x) for x in exl_sheet.row_values(i) ] + data.append(temp) + return json.dumps(data, encoding='utf-8') + +def save_to_xml(data, new_file_name): + root = etree.Element('root') + students = etree.SubElement(root, 'numbers') + students.append(etree.Comment(u"""数字信息""")) + students.text = data + + student_xml = etree.ElementTree(root) + student_xml.write(new_file_name, pretty_print=True, xml_declaration=True, encoding='utf-8') + + +if __name__ == '__main__': + content = read_exl('numbers.xls') + save_to_xml(content, 'numbers.xml') diff --git a/Jaccorot/0019/numbers.xls b/Jaccorot/0019/numbers.xls new file mode 100644 index 00000000..769bb4a1 Binary files /dev/null and b/Jaccorot/0019/numbers.xls differ diff --git a/Jaccorot/0019/numbers.xml b/Jaccorot/0019/numbers.xml new file mode 100644 index 00000000..1ba54401 --- /dev/null +++ b/Jaccorot/0019/numbers.xml @@ -0,0 +1,4 @@ + + + [[1, 82, 65535], [20, 90, 13], [26, 809, 1024]] + diff --git a/Jaccorot/0020/0020.py b/Jaccorot/0020/0020.py new file mode 100644 index 00000000..336126eb --- /dev/null +++ b/Jaccorot/0020/0020.py @@ -0,0 +1,25 @@ +#!/usr/bin/python +# coding=utf-8 + +""" +第 0020 题: 登陆中国联通网上营业厅 后选择「自助服务」 --> 「详单查询」,然后选择你要查询的时间段, +点击「查询」按钮,查询结果页面的最下方,点击「导出」,就会生成类似于 2014年10月01日~2014年10月31日 +通话详单.xls 文件。写代码,对每月通话时间做个统计。 +""" + +import xlrd + +def count_the_dail_time(filename): + excel = xlrd.open_workbook(filename) + sheet = excel.sheet_by_index(0) + row_nums = sheet.nrows + col_nums = sheet.ncols + total_time = 0 + for i in range(1,row_nums): + total_time += int(sheet.cell_value(i, 3)) + return total_time + + +if __name__ == "__main__": + total_len = count_the_dail_time("src.xls") + print "本月通话时长为" + total_len + "秒" diff --git a/Jaccorot/0020/src.xls b/Jaccorot/0020/src.xls new file mode 100644 index 00000000..3eb2fb39 Binary files /dev/null and b/Jaccorot/0020/src.xls differ diff --git a/Jaccorot/0021/0021.python b/Jaccorot/0021/0021.python new file mode 100644 index 00000000..ed78b95c --- /dev/null +++ b/Jaccorot/0021/0021.python @@ -0,0 +1,32 @@ +#!/usr/bin/python +# coding=utf-8 +__author__ = 'Jaccorot' + +import os +from hashlib import sha256 +from hmac import HMAC + +def encrypt_password(password, salt=None): + if salt is None: + salt = os.urandom(8) + assert 8 == len(salt) + assert isinstance(salt, str) + + if isinstance(password, unicode): + password = password.encode('utf-8') + assert isinstance(password, str) + + for i in range(10): + encrypted = HMAC(password, salt, sha256).digest() + return salt + encrypted + + +def validate_password(hashed, password): + return hashed == encrypt_password(password, hashed[:8]) + + +if __name__ == "__main__": + password_new = raw_input("Set your password\n") + password_saved = encrypt_password(password_new) + password_again = raw_input("Now,type in your password\n") + print "Yes,you got it." if validate_password(password_saved, password_again) else "No,it's wrong." diff --git a/Jaccorot/0022/0.jpg b/Jaccorot/0022/0.jpg new file mode 100644 index 00000000..82d17e99 Binary files /dev/null and b/Jaccorot/0022/0.jpg differ diff --git a/Jaccorot/0022/0022.py b/Jaccorot/0022/0022.py new file mode 100644 index 00000000..f817057b --- /dev/null +++ b/Jaccorot/0022/0022.py @@ -0,0 +1,40 @@ +#!/usr/local/bin/python +#coding=utf-8 + +""" +第 0022 题: iPhone 6、iPhone 6 Plus 早已上市开卖。请查看你写得 第 0005 题的代码是否可以复用。 +""" +import os +from PIL import Image + +PHONE = {'iPhone5':(1136,640), 'iPhone6':(1134,750), 'iPhone6P':(2208,1242)} + + +def resize_pic(path, new_path, phone_type): + im = Image.open(path) + w,h = im.size + + width,height = PHONE[phone_type] + + if w > width: + h = width * h // w + w = width + if h > height: + w = height * w // h + h = height + + im_resized = im.resize((w,h), Image.ANTIALIAS) + im_resized.save(new_path) + + +def walk_dir_and_resize(path, phone_type): + for root, dirs, files in os.walk(path): + for f_name in files: + if f_name.lower().endswith('jpg'): + path_dst = os.path.join(root,f_name) + f_new_name = phone_type + '_' + f_name + resize_pic(path=path_dst, new_path=f_new_name , phone_type=phone_type) + + +if __name__ == '__main__': + walk_dir_and_resize('./', 'iPhone6') diff --git a/Jaccorot/0023/guestbook.db b/Jaccorot/0023/guestbook.db new file mode 100644 index 00000000..a693ad0b Binary files /dev/null and b/Jaccorot/0023/guestbook.db differ diff --git a/Jaccorot/0023/guestbook.py b/Jaccorot/0023/guestbook.py new file mode 100644 index 00000000..be75c839 --- /dev/null +++ b/Jaccorot/0023/guestbook.py @@ -0,0 +1,75 @@ +import sqlite3 +from flask import Flask, request, session, g, redirect, url_for, abort, render_template, flash +from contextlib import closing +import time + +DATABASE = 'guestbook.db' +DEBUG = True +SECRET_KEY = 'development key' + +app = Flask(__name__) +app.config.from_object(__name__) + +def connect_db(): + return sqlite3.connect(app.config['DATABASE']) + +def init_db(): + with closing(connect_db()) as db: + with app.open_resource('schema.sql', mode='r') as f: + db.cursor().executescript(f.read()) + db.commit() + +@app.before_request +def before_request(): + g.db = connect_db() + +@app.teardown_request +def teardown_request(exception): + db = getattr(g, 'db', None) + if db is not None: + db.close() + g.db.close() + + +@app.route('/') +def show_entires(): + cur = g.db.execute('select name,text,time from entries order by id desc') + entries = [dict(name=row[0], text=row[1], time=row[2]) for row in cur.fetchall()] + for i in entries: + print i + return render_template('show_entries.html', entries=entries) + +@app.route('/add', methods=['POST']) +def add_entry(): + if not session.get('logged_in'): + abort(401) + current_time = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()) + g.db.execute('insert into entries (name, text, time) values (?, ?, ?)', + [request.form['name'], request.form['text'], current_time]) + g.db.commit() + flash('New entry was successfully posted') + return redirect(url_for('show_entires')) + +@app.route('/login', methods=['GET', 'POST']) +def login(): + error = None + if request.method == 'POST': + if request.form['username'] is None: + error = "Invalid username" + else: + session['logged_in'] = True + session['name'] = request.form['username'] + flash('You were logged in') + return redirect(url_for('show_entires')) + return render_template('login.html', error=error) + +@app.route('/logout') +def logout(): + session.pop('logged_in', None) + flash('You were logged out') + return redirect(url_for('show_entires')) + + + +if __name__ == "__main__": + app.run() diff --git a/Jaccorot/0023/schema.sql b/Jaccorot/0023/schema.sql new file mode 100644 index 00000000..37d58baa --- /dev/null +++ b/Jaccorot/0023/schema.sql @@ -0,0 +1,7 @@ +DROP TABLE if EXISTS entries; +CREATE TABLE entries( + id INTEGER PRIMARY KEY autoincrement, + name text NOT NULL , + text text NOT NULL, + time datetime NOT NULL +); \ No newline at end of file diff --git a/Jaccorot/0023/static/style.css b/Jaccorot/0023/static/style.css new file mode 100644 index 00000000..dbdb6f65 --- /dev/null +++ b/Jaccorot/0023/static/style.css @@ -0,0 +1,19 @@ +body { font-family: sans-serif; background: #eee; } +a, h1, h2 { color: #377ba8; } +h1, h2 { font-family: 'Georgia', serif; margin: 0; } +h1 { border-bottom: 2px solid #eee; } +h2 { font-size: 1.2em; } + +.page { margin: 2em auto; width: 35em; border: 5px solid #ccc; + padding: 0.8em; background: white; } +.entries { list-style: none; margin: 0; padding: 0; } +.entries li { margin: 0.8em 1.2em; } +.entries li h2 { margin-left: -1em; } +.add-entry { font-size: 0.9em; border-bottom: 1px solid #ccc; } +.add-entry dl { font-weight: bold; } +.metanav { text-align: right; font-size: 0.8em; padding: 0.3em; + margin-bottom: 1em; background: #fafafa; } +.flash { background: #cee5F5; padding: 0.5em; + border: 1px solid #aacbe2; } +.error { background: #f0d6d6; padding: 0.5em; } +.time { text-align:right; } \ No newline at end of file diff --git a/Jaccorot/0023/templates/layout.html b/Jaccorot/0023/templates/layout.html new file mode 100644 index 00000000..94cfdc84 --- /dev/null +++ b/Jaccorot/0023/templates/layout.html @@ -0,0 +1,25 @@ + + + + + Guestbook + + + +
+

Guestbook

+
+ {% if not session.logged_in %} + log in + {% else %} +
{{ session.name }}
+ log out + {% endif %} +
+ {% for message in get_flashed_messages() %} +
{{ message }}
+ {% endfor %} + {% block body %}{% endblock %} +
+ + \ No newline at end of file diff --git a/Jaccorot/0023/templates/login.html b/Jaccorot/0023/templates/login.html new file mode 100644 index 00000000..10693d19 --- /dev/null +++ b/Jaccorot/0023/templates/login.html @@ -0,0 +1,14 @@ +{% extends "layout.html" %} +{% block body %} +

Login

+ {% if error %} +

Error:{{ error }}

+ {% endif %} +
+
+
Username:
+
+
+
+
+{% endblock %} \ No newline at end of file diff --git a/Jaccorot/0023/templates/show_entries.html b/Jaccorot/0023/templates/show_entries.html new file mode 100644 index 00000000..dd248e15 --- /dev/null +++ b/Jaccorot/0023/templates/show_entries.html @@ -0,0 +1,25 @@ +{% extends "layout.html" %} +{% block body %} + {% if session.logged_in %} +
+
+
Text:
+
+
+ +
+
+ {% endif %} +
    + {% for entry in entries %} +
  • +

    {{ entry.name }}

    +
    {{ entry.time }}
    + {{ entry.text|safe }} + +
  • + {% else %} +
  • Unbelieveable. No entries here so far
  • + {% endfor %} +
+{% endblock %} \ No newline at end of file diff --git a/Jaccorot/0024/0024.md b/Jaccorot/0024/0024.md new file mode 100644 index 00000000..e6cc00cd --- /dev/null +++ b/Jaccorot/0024/0024.md @@ -0,0 +1,3 @@ +project link = +https://github.com/Jaccorot/DailyProject + diff --git a/JiYouMCC b/JiYouMCC new file mode 160000 index 00000000..e0c7c1c3 --- /dev/null +++ b/JiYouMCC @@ -0,0 +1 @@ +Subproject commit e0c7c1c37ccba38671078e0b0ff6238992a11499 diff --git a/JiYouMCC/0000/0000.png b/JiYouMCC/0000/0000.png deleted file mode 100644 index 4f6dd404..00000000 Binary files a/JiYouMCC/0000/0000.png and /dev/null differ diff --git a/JiYouMCC/0000/0000.py b/JiYouMCC/0000/0000.py deleted file mode 100644 index 0c2e3a44..00000000 --- a/JiYouMCC/0000/0000.py +++ /dev/null @@ -1,23 +0,0 @@ -# -*- coding: utf-8 -*- -# 第0000题:将你的QQ头像(或者微博头像)右上角加上红色的数字,类似于微信未读信息数量那种提示。 - -# using PIL in http://www.lfd.uci.edu/~gohlke/pythonlibs/#pillow -from PIL import Image -from PIL import ImageFont -from PIL import ImageDraw - - -def write_number(image_file_path, number=1): - img = Image.open(image_file_path) - font_size = img.size[0] if img.size[0] < img.size[1] else img.size[1] - font_size = font_size / 4 - number_txt = str(number) + ' ' if number < 100 else '99+' - font = ImageFont.truetype("arial.ttf", size=font_size) - if font.getsize(number_txt)[0] > img.size[0] or font.getsize(number_txt)[1] > img.size[1]: - return img - position = img.size[0] - font.getsize(number_txt)[0] - ImageDraw.Draw(img).text((position, 0), number_txt, (255, 0, 0), font) - return img - -write_number('0000.png').save('result.png') -write_number('0000.png', 100).save('result100.png') diff --git a/JiYouMCC/0001/0001.py b/JiYouMCC/0001/0001.py deleted file mode 100644 index 41f6912c..00000000 --- a/JiYouMCC/0001/0001.py +++ /dev/null @@ -1,17 +0,0 @@ -# -*- coding: utf-8 -*- -# 做为 Apple Store App 独立开发者,你要搞限时促销,为你的应用生成激活码(或者优惠券),使用 Python 如何生成 200 个激活码(或者优惠券)? - -import uuid - - -def create_code(number=200): - result = [] - while True is True: - temp = str(uuid.uuid1()).replace('-', '') - if not temp in result: - result.append(temp) - if len(result) is number: - break - return result - -print create_code() diff --git a/JiYouMCC/0002/0002.py b/JiYouMCC/0002/0002.py deleted file mode 100644 index be47dd5c..00000000 --- a/JiYouMCC/0002/0002.py +++ /dev/null @@ -1,78 +0,0 @@ -# -*- coding: utf-8 -*- -# 第 0002 题:将 0001 题生成的 200 个激活码(或者优惠券)保存到 MySQL 关系型数据库中。 -# using sina app -# test page:http://mccatcivitas.sinaapp.com/showmecode2 -import sae.const -import MySQLdb -import uuid - - -def create_code(number=200): - result = [] - while True is True: - temp = str(uuid.uuid1()).replace('-', '') - if not temp in result: - result.append(temp) - if len(result) is number: - break - return result - - -def insertCode(code, table='app_mccatcivitas.showmethecode'): - conn = MySQLdb.connect( - host=sae.const.MYSQL_HOST, - user=sae.const.MYSQL_USER, - passwd=sae.const.MYSQL_PASS, - port=int(sae.const.MYSQL_PORT), - charset='utf8') - cur = conn.cursor() - cur.execute("""insert into %s values('%s')""" % ( - table, code)) - conn.commit() - cur.close() - conn.close() - - -def selectCodes(table='app_mccatcivitas.showmethecode'): - connection = MySQLdb.connect( - host=sae.const.MYSQL_HOST, - user=sae.const.MYSQL_USER, - passwd=sae.const.MYSQL_PASS, - port=int(sae.const.MYSQL_PORT), - init_command='set names utf8') - cur = connection.cursor() - cur.execute("""select * from %s""" % (table)) - result = [] - rows = cur.fetchall() - for row in rows: - result.append(str(row[0])) - return result - - -def cleanUp(table='app_mccatcivitas.showmethecode'): - connection = MySQLdb.connect( - host=sae.const.MYSQL_HOST, - user=sae.const.MYSQL_USER, - passwd=sae.const.MYSQL_PASS, - port=int(sae.const.MYSQL_PORT), - init_command='set names utf8') - cur = connection.cursor() - try: - cur.execute("""drop table %s""" % (table)) - except Exception, e: - print e - connection.commit() - cur.execute( - """create table %s (code char(32) not null primary key)""" % (table)) - connection.commit() - cur.close() - connection.close() - - -def Process(): - cleanUp() - code = create_code() - for c in code: - insertCode(c) - result = selectCodes() - return result diff --git a/JiYouMCC/0003/0003.py b/JiYouMCC/0003/0003.py deleted file mode 100644 index a451b9fa..00000000 --- a/JiYouMCC/0003/0003.py +++ /dev/null @@ -1,3 +0,0 @@ -# -*- coding: utf-8 -*- -# 第 0003 题:将 0001 题生成的 200 个激活码(或者优惠券)保存到 Redis 非关系型数据库中。 -# fail to install redis, skip it \ No newline at end of file diff --git a/JiYouMCC/0004/0004.py b/JiYouMCC/0004/0004.py deleted file mode 100644 index 88819249..00000000 --- a/JiYouMCC/0004/0004.py +++ /dev/null @@ -1,28 +0,0 @@ -# -*- coding: utf-8 -*- -# 第 0004 题:任一个英文的纯文本文件,统计其中的单词出现的个数。 -import io -import operator - - -def get_count_table(file='0004.txt', ignore=[',', '.', ':', '!', '?', '”', '“', '1', '2', '3', '4', '5', '6', '7', '8', '9', '0'], lower=True): - txt = open(file).read() - for i in ignore: - txt = txt.replace(i, ' ') - if lower: - txt = txt.lower() - words = txt.split(' ') - dic = {} - for word in words: - if word is '': - continue - if word in dic: - dic[word] += 1 - else: - dic[word] = 1 - return dic - - -result = sorted( - get_count_table().items(), key=operator.itemgetter(1), reverse=True) -for item in result: - print item[0], item[1] diff --git a/JiYouMCC/0004/0004.txt b/JiYouMCC/0004/0004.txt deleted file mode 100644 index 8d9df9b6..00000000 --- a/JiYouMCC/0004/0004.txt +++ /dev/null @@ -1 +0,0 @@ -Then I looked, and behold, on Mount Zion stood the Lamb, and with him 144,000 who had his name and his Father’s name written on their foreheads.And I heard a voice from heaven like the roar of many waters and like the sound of loud thunder. The voice I heard was like the sound of harpists playing on their harps,and they were singing a new song before the throne and before the four living creatures and before the elders. No one could learn that song except the 144,000 who had been redeemed from the earth.It is these who have not defiled themselves with women, for they are virgins. It is these who follow the Lamb wherever he goes. These have been redeemed from mankind as firstfruits for God and the Lamb,and in their mouth no lie was found, for they are blameless.The Messages of the Three AngelsThen I saw another angel flying directly overhead, with an eternal gospel to proclaim to those who dwell on earth, to every nation and tribe and language and people.And he said with a loud voice, “Fear God and give him glory, because the hour of his judgment has come, and worship him who made heaven and earth, the sea and the springs of water.”Another angel, a second, followed, saying, “Fallen, fallen is Babylon the great, she who made all nations drink the wine of the passion1 of her sexual immorality.”And another angel, a third, followed them, saying with a loud voice, “If anyone worships the beast and its image and receives a mark on his forehead or on his hand,10 he also will drink the wine of God’s wrath, poured full strength into the cup of his anger, and he will be tormented with fire and sulfur in the presence of the holy angels and in the presence of the Lamb.And the smoke of their torment goes up forever and ever, and they have no rest, day or night, these worshipers of the beast and its image, and whoever receives the mark of its name.”Here is a call for the endurance of the saints, those who keep the commandments of God and their faith in Jesus.2And I heard a voice from heaven saying, “Write this: Blessed are the dead who die in the Lord from now on.” “Blessed indeed,” says the Spirit, “that they may rest from their labors, for their deeds follow them!”The Harvest of the EarthThen I looked, and behold, a white cloud, and seated on the cloud one like a son of man, with a golden crown on his head, and a sharp sickle in his hand.And another angel came out of the temple, calling with a loud voice to him who sat on the cloud, “Put in your sickle, and reap, for the hour to reap has come, for the harvest of the earth is fully ripe.”So he who sat on the cloud swung his sickle across the earth, and the earth was reaped.Then another angel came out of the temple in heaven, and he too had a sharp sickle.And another angel came out from the altar, the angel who has authority over the fire, and he called with a loud voice to the one who had the sharp sickle, “Put in your sickle and gather the clusters from the vine of the earth, for its grapes are ripe.”So the angel swung his sickle across the earth and gathered the grape harvest of the earth and threw it into the great winepress of the wrath of God.And the winepress was trodden outside the city, and blood flowed from the winepress, as high as a horse’s bridle, for 1,600 stadia. \ No newline at end of file diff --git a/JiYouMCC/0005/0005-r.jpg b/JiYouMCC/0005/0005-r.jpg deleted file mode 100644 index 0c7bca95..00000000 Binary files a/JiYouMCC/0005/0005-r.jpg and /dev/null differ diff --git a/JiYouMCC/0005/0005.jpg b/JiYouMCC/0005/0005.jpg deleted file mode 100644 index 030ab8a6..00000000 Binary files a/JiYouMCC/0005/0005.jpg and /dev/null differ diff --git a/JiYouMCC/0005/0005.py b/JiYouMCC/0005/0005.py deleted file mode 100644 index 6438fd06..00000000 --- a/JiYouMCC/0005/0005.py +++ /dev/null @@ -1,14 +0,0 @@ -# -*- coding: utf-8 -*- -# 第 0005 题:你有一个目录,装了很多照片,把它们的尺寸变成都不大于 iPhone5 分辨率的大小。 -# using PIL in http://www.lfd.uci.edu/~gohlke/pythonlibs/#pillow -from PIL import Image - - -def change_image_size(image_path='0005.jpg', size=(1136, 640)): - im = Image.open(image_path) - size = (size[1], size[0]) if im.size[1] > im.size[0] else size - im.thumbnail(size, Image.ANTIALIAS) - im.save('result-' + image_path) - -change_image_size('0005-r.jpg') -change_image_size('0005.jpg') diff --git a/JiYouMCC/0013/0013.md b/JiYouMCC/0013/0013.md deleted file mode 100644 index 50709047..00000000 --- a/JiYouMCC/0013/0013.md +++ /dev/null @@ -1,9 +0,0 @@ -# 第 0013 题: 用 Python 写一个爬图片的程序,爬 [这个链接里](http://tieba.baidu.com/p/2166231880)的日本妹子图片 :-) # - ----- - -其实我是我为了爬我自己一个[老博客](http://ycool.com/post/ae3u4zu)上面的图片才做这题的。。 - -我很懒惰没用啥爬虫架构请无视.. - -百度贴吧上面格式绝对没有我老博客上那么老实,就将就下吧 \ No newline at end of file diff --git a/JiYouMCC/0013/0013.py b/JiYouMCC/0013/0013.py deleted file mode 100644 index ec1388ef..00000000 --- a/JiYouMCC/0013/0013.py +++ /dev/null @@ -1,46 +0,0 @@ -import urllib2 -import urllib -import re -import os -import uuid - - -def get_images(html_url='http://ycool.com/post/ae3u4zu', - folder_name='jiyou_blog_PingLiangRoad', - extensions=['gif', 'jpg', 'png']): - request_html = urllib2.Request(html_url) - try: - response = urllib2.urlopen(request_html) - html = response.read() - r1 = r' im.size[0] else size - im.thumbnail(size, Image.ANTIALIAS) - im.save('result-' + image_path) - -change_image_size('0005-r.jpg') -change_image_size('0005.jpg') - -# ip6 -change_image_size(image_path='0005.jpg', size=(1334, 750)) - -# ip6plus -change_image_size(image_path='0005.jpg', size=(1920, 1080)) diff --git a/JiYouMCC/0023/0023.md b/JiYouMCC/0023/0023.md deleted file mode 100644 index 1d97dbed..00000000 --- a/JiYouMCC/0023/0023.md +++ /dev/null @@ -1,17 +0,0 @@ -第 0023 题: 使用 Python 的 Web 框架,做一个 Web 版本 留言簿 应用。 ---------------------------------------- - -以前在sea上弄过一个差不多的:http://jillyou.sinaapp.com/guest/ -不过sea弄django syncdb比较痛苦,所有sql拼接出的 -直接django真够傻瓜的…… - -代码版本用的sqlite3,本地调试的时候用的mysql - - 'default': { - 'ENGINE': 'django.db.backends.mysql', - 'NAME': 'guestbook', - 'USER': '', - 'PASSWORD': '', - 'HOST': '', - 'PORT': '', - } diff --git a/JiYouMCC/0023/guestbook/guestbook/commits/admin.py b/JiYouMCC/0023/guestbook/guestbook/commits/admin.py deleted file mode 100644 index c7687ca1..00000000 --- a/JiYouMCC/0023/guestbook/guestbook/commits/admin.py +++ /dev/null @@ -1,4 +0,0 @@ -from django.contrib import admin -from models import Message - -admin.site.register(Message) diff --git a/JiYouMCC/0023/guestbook/guestbook/commits/migrations/0001_initial.py b/JiYouMCC/0023/guestbook/guestbook/commits/migrations/0001_initial.py deleted file mode 100644 index 2d6f846a..00000000 --- a/JiYouMCC/0023/guestbook/guestbook/commits/migrations/0001_initial.py +++ /dev/null @@ -1,22 +0,0 @@ -# -*- coding: utf-8 -*- -from __future__ import unicode_literals -from django.db import models, migrations - - -class Migration(migrations.Migration): - dependencies = [] - operations = [ - migrations.CreateModel( - name='Message', - fields=[ - ('id', models.AutoField( - verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), - ('name', models.CharField(max_length=30)), - ('message', models.TextField(max_length=65535)), - ('date', models.DateTimeField()), - ], - options={ - }, - bases=(models.Model,), - ), - ] diff --git a/JiYouMCC/0023/guestbook/guestbook/commits/models.py b/JiYouMCC/0023/guestbook/guestbook/commits/models.py deleted file mode 100644 index 074387a7..00000000 --- a/JiYouMCC/0023/guestbook/guestbook/commits/models.py +++ /dev/null @@ -1,10 +0,0 @@ -from django.db import models - - -class Message(models.Model): - name = models.CharField(max_length=30) - message = models.TextField(max_length=65535) - date = models.DateTimeField() - - def __unicode__(self): - return self.name + ':' + self.message[:25] diff --git a/JiYouMCC/0023/guestbook/guestbook/commits/tests.py b/JiYouMCC/0023/guestbook/guestbook/commits/tests.py deleted file mode 100644 index 2e9cb5f6..00000000 --- a/JiYouMCC/0023/guestbook/guestbook/commits/tests.py +++ /dev/null @@ -1 +0,0 @@ -from django.test import TestCase diff --git a/JiYouMCC/0023/guestbook/guestbook/commits/views.py b/JiYouMCC/0023/guestbook/guestbook/commits/views.py deleted file mode 100644 index b9263bc3..00000000 --- a/JiYouMCC/0023/guestbook/guestbook/commits/views.py +++ /dev/null @@ -1,36 +0,0 @@ -# -*- coding: utf-8 -*- -from django.shortcuts import render -from django.http import HttpResponse, HttpResponseRedirect -import datetime -from models import Message - - -def guestbook(request): - try: - name = request.COOKIES["name"] - except: - name = u"这家伙连名字也没有" - return render(request, 'guestbook.html', {'commits': selectTextMsg(), 'name': name}) - - -def guesttalk(request): - response = HttpResponseRedirect("/guest") - if request.method == "GET": - name = request.GET.get('name', '') - commit = request.GET.get('commits', '') - date = datetime.datetime.now() - if len(name) > 0 and len(commit) > 0 and len(name) < 41 and len(commit) < 4096: - response.set_cookie("name", name.encode('utf8')) - insertTextMsg(name, date, commit) - return response - - -def insertTextMsg(user, date, message): - message = Message(name=user, - message=message, - date=date,) - message.save() - - -def selectTextMsg(): - return Message.objects.all().order_by("-date") diff --git a/JiYouMCC/0023/guestbook/guestbook/settings.py b/JiYouMCC/0023/guestbook/guestbook/settings.py deleted file mode 100644 index c25a6cc8..00000000 --- a/JiYouMCC/0023/guestbook/guestbook/settings.py +++ /dev/null @@ -1,41 +0,0 @@ -import os -BASE_DIR = os.path.dirname(os.path.dirname(__file__)) -SECRET_KEY = '+m8si5lo@6467j75%wz#z+cvsxl=)u_c(2-o^&+&^++*-48t$5' -DEBUG = True -TEMPLATE_DEBUG = True -ALLOWED_HOSTS = [] -INSTALLED_APPS = ( - 'django.contrib.admin', - 'django.contrib.auth', - 'django.contrib.contenttypes', - 'django.contrib.sessions', - 'django.contrib.messages', - 'django.contrib.staticfiles', - 'guestbook.commits', -) -MIDDLEWARE_CLASSES = ( - 'django.contrib.sessions.middleware.SessionMiddleware', - 'django.middleware.common.CommonMiddleware', - 'django.middleware.csrf.CsrfViewMiddleware', - 'django.contrib.auth.middleware.AuthenticationMiddleware', - 'django.contrib.auth.middleware.SessionAuthenticationMiddleware', - 'django.contrib.messages.middleware.MessageMiddleware', - 'django.middleware.clickjacking.XFrameOptionsMiddleware', -) -ROOT_URLCONF = 'guestbook.urls' -WSGI_APPLICATION = 'guestbook.wsgi.application' -DATABASES = { - 'default': { - 'ENGINE': 'django.db.backends.sqlite3', - 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), - } -} -LANGUAGE_CODE = 'zh-cn' -TIME_ZONE = 'Asia/Shanghai' -USE_I18N = True -USE_L10N = True -USE_TZ = True -STATIC_URL = '/static/' -TEMPLATE_DIRS = ( - os.path.join(BASE_DIR, 'guestbook/template'), -) diff --git a/JiYouMCC/0023/guestbook/guestbook/template/guestbook.html b/JiYouMCC/0023/guestbook/guestbook/template/guestbook.html deleted file mode 100644 index ce2cfe5a..00000000 --- a/JiYouMCC/0023/guestbook/guestbook/template/guestbook.html +++ /dev/null @@ -1,25 +0,0 @@ - - - - 简易留言本 - - -

简易留言本

-
- 名字: -
- -
- - -
-
- {% for commit in commits %} -
-

{{ commit.date|date:"Y-n-j H:i:s" }} {{ commit.name }}

-
-
{{ commit.message|escape|linebreaks|wordwrap:"75" }}
- {% endfor %} -
- - \ No newline at end of file diff --git a/JiYouMCC/0023/guestbook/guestbook/urls.py b/JiYouMCC/0023/guestbook/guestbook/urls.py deleted file mode 100644 index 80fdc930..00000000 --- a/JiYouMCC/0023/guestbook/guestbook/urls.py +++ /dev/null @@ -1,9 +0,0 @@ -from django.conf.urls import patterns, include, url -from django.contrib import admin -from commits.views import guestbook, guesttalk - -urlpatterns = patterns('', - url(r'^admin/', include(admin.site.urls)), - url(r'^guest/', guestbook), - url(r'^guesttalk', guesttalk), - ) diff --git a/JiYouMCC/0023/guestbook/guestbook/wsgi.py b/JiYouMCC/0023/guestbook/guestbook/wsgi.py deleted file mode 100644 index 02297548..00000000 --- a/JiYouMCC/0023/guestbook/guestbook/wsgi.py +++ /dev/null @@ -1,5 +0,0 @@ -import os -os.environ.setdefault("DJANGO_SETTINGS_MODULE", "guestbook.settings") - -from django.core.wsgi import get_wsgi_application -application = get_wsgi_application() diff --git a/JiYouMCC/0024/0024.md b/JiYouMCC/0024/0024.md deleted file mode 100644 index eb857b6c..00000000 --- a/JiYouMCC/0024/0024.md +++ /dev/null @@ -1,8 +0,0 @@ -第 0024 题: 使用 Python 的 Web 框架,做一个 Web 版本 TodoList 应用。 ---------------------------------------------------- -![任务列表](https://raw.githubusercontent.com/JiYouMCC/python/master/JiYouMCC/0024/0024.png) - -admin/admin -- 无限呆蠢的UI请忽略,这个实在是艺术活儿,原来还想把任务DragDrop到状态下和Jire的Kanban一样,没心思折腾html5了 -- 其实还加了duedate和createdate,不高兴整template了,不然弄起来就像any.do似的 -- 排序UI不高兴整了,就是Models.orderby的问题 diff --git a/JiYouMCC/0024/0024.png b/JiYouMCC/0024/0024.png deleted file mode 100644 index c72a9665..00000000 Binary files a/JiYouMCC/0024/0024.png and /dev/null differ diff --git a/JiYouMCC/0024/todoList/static/global.css b/JiYouMCC/0024/todoList/static/global.css deleted file mode 100644 index c2b5fd3c..00000000 --- a/JiYouMCC/0024/todoList/static/global.css +++ /dev/null @@ -1,44 +0,0 @@ -label { - width: 50%; - display:inline-block; - text-align: right; -} - -h1 { - text-align: center; -} - -.helptext { - display: block; - text-align: right; -} - -.b { - text-align:center; -} - -table { - width: 100%; - text-align: center; -} - -tr { - vertical-align:top; -} - -.list { - width: 300px; - border-style: solid; - border-width: 1px; - text-align: center; -} - -.next,.pre { - display: inline-block; - width:70px; -} - -.detail{ - display: inline-block; - width:150px; -} \ No newline at end of file diff --git a/JiYouMCC/0024/todoList/templates/process.html b/JiYouMCC/0024/todoList/templates/process.html deleted file mode 100644 index 15287c9a..00000000 --- a/JiYouMCC/0024/todoList/templates/process.html +++ /dev/null @@ -1,64 +0,0 @@ - - - {{ user_name }}的任务列表 - {% load staticfiles %} - - - -

{{ user_name }}的任务列表

-
我不是{{ user_name }}, 我要退出
-
- {% csrf_token %} - - - - - - - - - - -
添加新的任务
- -
-
- - - {% for item in status %} - - {% endfor %} - - - {% for item in lists %} - - {% endfor %} - -
{{ item.status }}
- {% for i in item %} -
- {% if not i.status = firststatus %} -
-
- {% csrf_token %} - - -
-
- {% endif %} -
- {{ i.detail}} -
- {% if not i.status = laststatus %} - - {% endif %} -
- {% endfor %} -
- \ No newline at end of file diff --git a/JiYouMCC/0024/todoList/templates/registration/login.html b/JiYouMCC/0024/todoList/templates/registration/login.html deleted file mode 100644 index b3c68ac3..00000000 --- a/JiYouMCC/0024/todoList/templates/registration/login.html +++ /dev/null @@ -1,23 +0,0 @@ - - - 登录 - {% load staticfiles %} - - - -

登录

-
- {% csrf_token %} - {{ form.as_p }} -
- - -
-
-
-
- -
-
- - \ No newline at end of file diff --git a/JiYouMCC/0024/todoList/templates/registration/register.html b/JiYouMCC/0024/todoList/templates/registration/register.html deleted file mode 100644 index c0fe2f72..00000000 --- a/JiYouMCC/0024/todoList/templates/registration/register.html +++ /dev/null @@ -1,17 +0,0 @@ - - - 注册 - {% load staticfiles %} - - - -

注册

-
- {% csrf_token %} - {{ form.as_p }} -
- -
-
- - \ No newline at end of file diff --git a/JiYouMCC/0024/todoList/todoList/list/admin.py b/JiYouMCC/0024/todoList/todoList/list/admin.py deleted file mode 100644 index c8c76313..00000000 --- a/JiYouMCC/0024/todoList/todoList/list/admin.py +++ /dev/null @@ -1,5 +0,0 @@ -from django.contrib import admin -from models import Status, List - -admin.site.register(Status) -admin.site.register(List) diff --git a/JiYouMCC/0024/todoList/todoList/list/models.py b/JiYouMCC/0024/todoList/todoList/list/models.py deleted file mode 100644 index d13cce26..00000000 --- a/JiYouMCC/0024/todoList/todoList/list/models.py +++ /dev/null @@ -1,20 +0,0 @@ -from django.db import models -from django.contrib.auth.models import User - - -class Status(models.Model): - status = models.CharField(max_length=30) - - def __unicode__(self): - return self.status - - -class List(models.Model): - user = models.ForeignKey(User) - createdate = models.DateTimeField() - duedate = models.DateTimeField() - detail = models.CharField(max_length=65535) - status = models.ForeignKey(Status) - - def __unicode__(self): - return self.detail diff --git a/JiYouMCC/0024/todoList/todoList/list/views.py b/JiYouMCC/0024/todoList/todoList/list/views.py deleted file mode 100644 index a83d6e77..00000000 --- a/JiYouMCC/0024/todoList/todoList/list/views.py +++ /dev/null @@ -1,40 +0,0 @@ -from django.shortcuts import render -from models import Status, List -import datetime - - -def get_first_status(): - return Status.objects.all()[0] - - -def get_last_status(): - return Status.objects.order_by('-id')[0] - - -def create_new_list(user, detail): - new_list = List( - user=user, - createdate=datetime.datetime.now(), - duedate=datetime.datetime.now(), - status=get_first_status(), - detail=detail - ) - new_list.save() - -def next_step_list(id): - try: - the_list = List.objects.get(id=id) - if not the_list.status is get_last_status(): - the_list.status = Status.objects.get(id=the_list.status.id + 1) - the_list.save() - except Exception, e: - print e - -def pre_step_list(id): - try: - the_list = List.objects.get(id=id) - if not the_list.status is get_first_status(): - the_list.status = Status.objects.get(id=the_list.status.id - 1) - the_list.save() - except Exception, e: - print e diff --git a/JiYouMCC/0024/todoList/todoList/settings.py b/JiYouMCC/0024/todoList/todoList/settings.py deleted file mode 100644 index a472e8de..00000000 --- a/JiYouMCC/0024/todoList/todoList/settings.py +++ /dev/null @@ -1,44 +0,0 @@ -import os -BASE_DIR = os.path.dirname(os.path.dirname(__file__)) -SECRET_KEY = 'b$zem$#&=e-mxu1&j-ntdn@v-iw5(y3tq5%mo2um0c3j-ab92k' -DEBUG = True -TEMPLATE_DEBUG = True -ALLOWED_HOSTS = [] -INSTALLED_APPS = ( - 'django.contrib.admin', - 'django.contrib.auth', - 'django.contrib.contenttypes', - 'django.contrib.sessions', - 'django.contrib.messages', - 'django.contrib.staticfiles', - 'todoList.list', -) -MIDDLEWARE_CLASSES = ( - 'django.contrib.sessions.middleware.SessionMiddleware', - 'django.middleware.common.CommonMiddleware', - 'django.middleware.csrf.CsrfViewMiddleware', - 'django.contrib.auth.middleware.AuthenticationMiddleware', - 'django.contrib.auth.middleware.SessionAuthenticationMiddleware', - 'django.contrib.messages.middleware.MessageMiddleware', - 'django.middleware.clickjacking.XFrameOptionsMiddleware', -) -ROOT_URLCONF = 'todoList.urls' -WSGI_APPLICATION = 'todoList.wsgi.application' -DATABASES = { - 'default': { - 'ENGINE': 'django.db.backends.sqlite3', - 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), - } -} -LANGUAGE_CODE = 'zh-cn' -TIME_ZONE = 'Asia/Shanghai' -USE_I18N = True -USE_L10N = True -USE_TZ = True -STATIC_URL = '/static/' -STATICFILES_DIRS = ( - os.path.join(BASE_DIR, 'static'), -) -TEMPLATE_DIRS = ( - os.path.join(BASE_DIR, 'templates'), -) diff --git a/JiYouMCC/0024/todoList/todoList/urls.py b/JiYouMCC/0024/todoList/todoList/urls.py deleted file mode 100644 index 5be7557c..00000000 --- a/JiYouMCC/0024/todoList/todoList/urls.py +++ /dev/null @@ -1,18 +0,0 @@ -from django.conf.urls import patterns, include, url -from django.contrib import admin -from django.contrib.auth.views import login, logout, redirect_to_login -from views import process, register - -from django.contrib.staticfiles.urls import staticfiles_urlpatterns - -urlpatterns = patterns('', - url(r'^admin/', include(admin.site.urls)), - url(r'^login/$', login, - {'extra_context': {'next': '/'}}), - url(r'^logout/$', logout, {'next_page': '/'}), - url(r'^redirect_to_login/$', redirect_to_login, - {'login_url': '/login'}), - url(r'^register/$', register), - url(r'^$', process), - ) -urlpatterns += staticfiles_urlpatterns() diff --git a/JiYouMCC/0024/todoList/todoList/views.py b/JiYouMCC/0024/todoList/todoList/views.py deleted file mode 100644 index a9ea069e..00000000 --- a/JiYouMCC/0024/todoList/todoList/views.py +++ /dev/null @@ -1,42 +0,0 @@ -from django.contrib.auth.forms import UserCreationForm -from django.contrib.auth.models import User -from django.http import HttpResponseRedirect -from django.shortcuts import render_to_response, RequestContext -from todoList.list.models import List, Status -from todoList.list.views import get_first_status, get_last_status, create_new_list, next_step_list,pre_step_list -import datetime - - -def process(request): - if not request.user.is_authenticated(): - return HttpResponseRedirect('/login/?next=%s' % request.path) - status_result = Status.objects.all() - if request.method == "POST": - if 'detail' in request.POST: - create_new_list(request.user, request.POST.get('detail')) - if 'next' in request.POST: - next_step_list(request.POST.get('next')) - if 'pre' in request.POST: - pre_step_list(request.POST.get('pre')) - list_result = [] - for item in status_result: - list_result.append(List.objects.filter(user=request.user, status=item)) - return render_to_response("process.html", - {'user_name': request.user, - 'status': status_result, - 'lists': list_result, - 'laststatus': get_last_status(), - 'firststatus': get_first_status() }, context_instance=RequestContext(request)) - - -def register(request): - if request.method == 'POST': - form = UserCreationForm(request.POST) - if form.is_valid(): - form.save() - return HttpResponseRedirect("/redirect_to_login") - else: - form = UserCreationForm() - return render_to_response("registration/register.html", - {'form': form, }, - context_instance=RequestContext(request),) diff --git a/Jimmy66/README.md b/Jimmy66/README.md new file mode 100644 index 00000000..60914929 --- /dev/null +++ b/Jimmy66/README.md @@ -0,0 +1,9 @@ +##My Repositorie + +You can view my solutions through this url. + +Feel free to give me some advice or ask some questions. + +If my code help your learning, I wish you will star my project. + +[https://github.com/starlightme/My-Solutions-For-Show-Me-the-Code](https://github.com/starlightme/My-Solutions-For-Show-Me-the-Code) diff --git a/Kxrr/0000/0000.py b/Kxrr/0000/0000.py new file mode 100644 index 00000000..f4422fa9 --- /dev/null +++ b/Kxrr/0000/0000.py @@ -0,0 +1,22 @@ +#!/usr/bin/env python +#-*- coding: utf-8 -*- +__author__ = 'Kxrr' + +from PIL import Image,ImageDraw,ImageFont +import random + +msgNum = str(random.randint(1,99)) + +# Read image +im = Image.open('kxrr.png') +w,h = im.size +wDraw = 0.8 * w +hDraw = 0.08 * w + +# Draw image +font = ImageFont.truetype('/usr/share/fonts/truetype/droid/DroidSans.ttf', 30) # use absolute font path to fix 'IOError: cannot open resource' +draw = ImageDraw.Draw(im) +draw.text((wDraw,hDraw), msgNum, font=font, fill=(255,33,33)) + +# Save image +im.save('kxrr_msg.png', 'png') \ No newline at end of file diff --git a/Kxrr/0000/kxrr.png b/Kxrr/0000/kxrr.png new file mode 100644 index 00000000..868c1d2e Binary files /dev/null and b/Kxrr/0000/kxrr.png differ diff --git a/Kxrr/0000/kxrr_msg.png b/Kxrr/0000/kxrr_msg.png new file mode 100644 index 00000000..747bedf7 Binary files /dev/null and b/Kxrr/0000/kxrr_msg.png differ diff --git a/Kxrr/0001/0001.py b/Kxrr/0001/0001.py new file mode 100644 index 00000000..f81c14ce --- /dev/null +++ b/Kxrr/0001/0001.py @@ -0,0 +1,19 @@ +#!/usr/bin/env python +# encoding: utf-8 +__author__ = 'Kxrr' + +import random, string + +ALL_LETTERS = string.ascii_uppercase + string.digits +codeAmount = 200 +codeRound = 10 +codeResult = [] + +while len(codeResult) != codeAmount: + everyCode =''.join((random.choice(ALL_LETTERS) for i in range(codeRound))) + if everyCode not in codeResult: + codeResult.append(everyCode) + +print len(codeResult) +print codeResult + diff --git a/Kxrr/0003/0003.py b/Kxrr/0003/0003.py new file mode 100644 index 00000000..bdc78bd1 --- /dev/null +++ b/Kxrr/0003/0003.py @@ -0,0 +1,23 @@ +#!/usr/bin/env python +#-*- coding: utf-8 -*- +__author__ = 'Kxrr' + +import redis + +REDIS_HOST = '127.0.0.1' +REDIS_PORT = 6379 + +cache = redis.StrictRedis(host=REDIS_HOST, port=REDIS_PORT, db=0) + +# Store +with open('codeResult.txt', 'r') as f: + keyList = [] + for lineNum, eachCode in enumerate(f.readlines()): + keyList.append(lineNum) + cache.set(str(lineNum), eachCode) + +# Read +for i in keyList: + print cache.get(str(i)) + + diff --git a/Kxrr/0003/codeResult.txt b/Kxrr/0003/codeResult.txt new file mode 100644 index 00000000..450d6c9c --- /dev/null +++ b/Kxrr/0003/codeResult.txt @@ -0,0 +1,200 @@ +OU29SQIAW2 +W2YU6Y69OD +PIUD0AD07X +A8MVZOVX46 +5ZZJVPKLPJ +PGBLUUY35S +9X69SD6GBL +EO6X9ALS9X +NAH6TA659D +Z9XLBJWW57 +EIAWKME1HX +HAMWQJSTX3 +UFH4IB71SJ +P6MRJWATJJ +2JDDWLI6RA +2E8GOX7IKW +2WP9BDAZJV +ZRHHH4WV3O +NRC6TA2QS2 +YJI75X0UAA +GNUAHR1KV2 +75E790JYPR +UAFRKJASBI +YQVW9Y1MVH +4EL7B731JR +BNVGGARHI0 +EA0K2Q9DQ1 +PC5KTRZHIC +RYGHI5EM4P +U8RN9IP0DA +NWTP93BLP9 +IANU2MZAV4 +7VSCVKAG1S +2KYMZ4TL3F +7614J1QCHU +L29L5WZ5TY +KHB20I2OBU +Y2NKBG9N06 +758QKKTWFH +SYGEUJT4IK +5YS95CYACU +DQSJ6L9W7B +5QAHM82X6X +SAP8IBDVEF +CODQ7LMYG0 +WQVHFZ89WT +61A4QC5XAH +2RW8HT3LHW +0DE6HKQDF2 +JI4E5CYN3L +Y41ULGK67H +276AKNX81I +XOVU8S5BI6 +BBNI4RXS01 +WMQ8H6YL69 +S3MFA27NDU +R6BY1ZOWQ8 +94OA4YBFEV +50JB1H74KZ +HS908KHA0G +W0BYT5S7EN +22BYQ4ABEO +V4RV6KMUP7 +EH5T1YQZL6 +XVAHH2FSZ4 +CV88ZT86PB +O9RT961QOG +YQVCGBKPZO +3RJEG8HIHJ +ST8FSBPCW5 +UXVG32CTZG +XNMQRXMB4D +NQQH7VG4C6 +LZ3VRXBR4O +ZY9CQB3D34 +GRCTV0LSEY +K372NS7L38 +9J6WRQRLE0 +HGDWUGPY20 +9H2FLDOGK7 +OJ0MK0ZGCK +XI0GWBNTIB +HE8THGP5W3 +3UU85SOPYN +ZDWG0HUU5R +Z0TIX1S0TR +749V4Y2A7W +WKQSX4LQLX +YUXPTZJ0Z0 +TKYWZTVTTX +0IP53OCENN +GWZKN21LHT +62K3XRGTUM +647Q6Q9JDQ +2JNA0EG5HP +OV497711S5 +SAB9WTZXVR +2O82J9JP11 +0VPAZT93TS +EYVNVFOF51 +NV9OK1RGR7 +CZTSTR1595 +JYYU6N9VUE +X3K1VO53DQ +VH2A7CJR55 +UYN58BISXY +UKQIAL3PTN +3GG0UX0XYW +S6BVDBIBAK +MI6EQTTU3U +MPQTMI8LQ4 +PIL7SMZCV4 +EISUEPYZMB +TNOW06L42F +CRRGUFUNT0 +QY5AFODE7N +TXARYT5T9S +2F1QHQI62Q +MN27OH85IO +CLE4PX9TRA +EBPHSXJZ6U +6UAQHOIN8X +KW4ENLYMH3 +41OUVI11TL +B7X0RNY3YK +U5QY0OHXMF +S13VGA3DYO +TWMDSW11HG +LSGXDBJZ8Q +QCILHG6HS6 +ZZM7N8VFY1 +QWCDTBDVC3 +85BVJF3UKL +SJJUMP3YOC +WPWZ3G1MEY +3P5SBZ3WXJ +270YHBTINI +ZD2HQSUHSV +FTDOK22DEQ +06JA0RCAIP +ZHILS2UB2N +0H30QRZ6RF +4RI7CWSFUC +B1XVETOB9I +NPI14U9U5F +KFCVIROJTB +0Y8UTS2BQP +ENJC3S0IDF +RNVJK8SU0J +6ONNUQLMD1 +ZRUKNKOR7W +JBPRC75ZUH +5Q7PKD3NGM +LSTYXQHWGS +07HSFSKZRB +PX9A56VNAM +AGBPWS82E4 +NLJEBMS1K0 +569NPPBMBW +Y5B8LYLUFI +8I3IR8CEDX +DGW1YBHNE7 +JI6VN3UQ5S +YCVVE3TRDN +WBR1UGYT9L +8TL351B8VH +EYLC00Q88I +MZ544ITY9V +0M5V3AV7VW +DM1RXV2RZM +CL4UTYH2KK +RYP0J5S2MB +G01LYVCFSO +99XLJ2J96O +2EQR4E7YJU +MZGYSJ5HAO +GYFOPU72Y1 +73NIVD6MET +2W6VS5TSKB +YOXA7LWQIO +TUSEYN4HGX +RH5DJKWGMY +BE16XQOOHV +4RNREWW7SH +AW8FIO68MN +0K2ZJS3YVO +OYSDYZSSGG +M2P4EB3Y7Q +7ZHXYHFXHS +Z870E73IDS +FMLSSK2N5G +K58P7PVVF4 +NPKXENQDN1 +3YZ9OWLM3J +WRTGTVYECM +B8N0AJRYQV +VBMFFBF9OO +K489UH2WSP +11WY1FARCF +0W0HHYHKGS \ No newline at end of file diff --git a/Kxrr/0004/0004.py b/Kxrr/0004/0004.py new file mode 100644 index 00000000..aa852603 --- /dev/null +++ b/Kxrr/0004/0004.py @@ -0,0 +1,22 @@ +#!/usr/bin/env python +# encoding: utf-8 +__author__ = 'Kxrr' + +import re + +with open('0004.txt', 'r') as f: + dictResult = {} + + # Find the letters each line + for line in f.readlines(): + listMatch = re.findall('[a-zA-Z]+', line.lower()) # remember to lower the letters + + # Count + for eachLetter in listMatch: + eachLetterCount = len(re.findall(eachLetter, line.lower())) + dictResult[eachLetter] = dictResult.get(eachLetter, 0) + eachLetterCount + + # Sort the result + result = sorted(dictResult.items(), key=lambda d: d[1], reverse=True) + for each in result: + print each \ No newline at end of file diff --git a/Kxrr/0004/0004.txt b/Kxrr/0004/0004.txt new file mode 100644 index 00000000..254d1ae9 --- /dev/null +++ b/Kxrr/0004/0004.txt @@ -0,0 +1,100 @@ +The entrepreneur teaching Japan how to take more risks +By Hoang Nguyen BBC reporter, Tokyo + + 14 September 2015 + From the section Business + + Jump media player + Media player help + Out of media player. Press enter to return or tab to continue. + Media caption Serial start-up businessman William Saito is on a mission to make Japan more entrepreneurial + The Boss + + The 21-year-old building India's largest hotel network + A hair-raising way to start make money + Revolutionising motorcycle taxis + Vietnam's start-up queen + + When William Saito quit as a medical doctor immediately after qualifying, his parents refused to speak to him for two years. + + But they're not complaining about the end result now, says the 44-year-old Japanese American. + + He did the training to fulfil his parents' dream of him becoming a doctor, and as he jokes, his parents never actually said how long they wanted him to be a doctor for - just to be one. + + The reason he left so soon was because he was determined to carry on the venture he'd begun at just 11-years-old while still in junior high school. + + He had founded his own start-up company, which eventually focused on enhanced security for personal computers through technologies such as fingerprint and iris recognition. + + Mr Saito formally incorporated the firm - I/O Software - in 1991 while he was at university. The company became a leader in biometrics and information security, and just 14 years later at the age of 33 he sold it to US giant Microsoft. + + While the terms of the deal mean he can't reveal the price he received, Mr Saito admits he would have been in a position to retire then if he'd wanted to. + + But unsurprisingly for someone so driven at such a young age, he has continued to work relentlessly, using his experience to help other entrepreneurs, particularly in his parents' home country of Japan. + Image copyright William Saito + Image caption William Saito has always had his finger in several pies + + While born and raised in the US, Mr Saito still believes he "owes the Japanese", because it's his heritage which he credits for his success. And now he believes he can give something back. + 'Changed my life' + + Mr Saito's parents couldn't speak English when they emigrated to the US, settling in Los Angeles in California, just two years before he was born in 1971. + + Determined to give their son - the eldest of three - a competitive advantage to ensure he would thrive in their new country, they focused on mathematics, bringing over complex textbooks from Japan, and teaching him things well beyond the expected level for his age. + + "That turned into a huge advantage for me," he says. + + In fact, his maths became so advanced that his teacher ran out of suitable lessons, suggesting he played with "a thing called a personal computer" instead. + + "I was able to take advantage of this lead and it changed my life," Mr Saito says. + Image copyright William Saito + Image caption William Saito is particularly keen to support female Japanese entrepreneurs + + On this teacher's advice, his parents took out a home loan to buy him his very own personal computer - worth about $5,000 (£3,200) in today's money - which from their point of view was aimed at helping him become a doctor. + + But some work, organised by the same teacher, changed the direction of his life permanently. The teacher suggested to a friend - an accountant at investment bank Merrill Lynch - that Mr Saito, who at the time was just 10-years-old, could help with writing computer programmes. + + "When I finished I received a cheque, and I didn't expect that. + + "That really changed my view about doing something fun, but at the same time getting paid for it. It was definitely a wake-up moment for me," he says. + + Despite his precocious start, Mr Saito denies that he was hot-housed, saying his parents exposed him to lots of different activities, and made it clear that success was about more than just good grades. + + In particular, he says both the schools he went to, and his parents, emphasised the importance of volunteering. + + It's a lesson he has taken to heart, and since the successful sale of his first firm, he has worked hard to support other would-be entrepreneurs. + + He confesses one of his favourite pursuits, is judging business plans, and he travels globally to do this. To date, he calculates he's judged some 15,000 people in such competitions. + + But his main focus is his parents' home country of Japan. + 'Giving back' + + In 2005, after selling I/O Software, he moved to Japan and founded venture capital firm and consultancy InTecur. + + He also works as a special adviser for the Japanese government, specialising in cybersecurity. + + But his main drive is to make the Japanese more entrepreneurial. + Image copyright William Saito + Image caption William Saito's family always had high hopes for him + Image copyright William Saito + Image caption As a child he was interested in many different things + + As well as advising firms on various technology issues, InTecur aims to help young Japanese technology entrepreneurs become successful, something which he feels the Japanese culture, which typically bases seniority on age and experience, makes difficult. + + "People in their 20s aren't given the opportunity. So for me I felt an obligation to give back to that next generation because I was given the opportunity," he says. + Image copyright William Saito + Image caption His parents hoped he would become a medical doctor + Image copyright William Saito + Image caption Mr Saito cannot reveal the price that Microsoft paid him for I/O Software + + So far, the firm has invested in 24 companies, 14 of which are run by women - who he believes are also often overlooked in Japanese society. + + He says he also makes a point of investing in people who have previously failed. + + "Failure here [in Japan] is a bad word. I'm the reverse. You have to fail once and gain that experience first, then you know what your weaknesses and strengths are." + + It is these attitudes, which he believes are stifling Japan's entrepreneurial spirit and making it harder for the country to grow. + + But he's optimistic that things are changing. And it's this which makes him happiest. + + "To unleash that potential and to see people make real change, I think I'm most proud about that. + + "This is still an unfinished story but it's starting to take root," he says. diff --git a/Kxrr/README.md b/Kxrr/README.md new file mode 100644 index 00000000..01717403 --- /dev/null +++ b/Kxrr/README.md @@ -0,0 +1,201 @@ +## Python 练习册,每天一个小程序 ## + + +#### 说明: #### + +- Python 练习册,每天一个小程序。注:将 Python 换成其他语言,大多数题目也适用 +- 不会出现诸如「打印九九乘法表」、「打印水仙花」之类的题目 +- 本文本文由@史江歌(shijiangge@gmail.com QQ:499065469)根据互联网资料收集整理而成,感谢互联网,感谢各位的分享。鸣谢!本文会不断更新。 +- 欢迎大家 Pull Request 出题目,贴代码(Gist、Blog皆可):-) +- 欢迎解答, 并发送 pull request 到 [Show-Me-the-Code](https://github.com/Show-Me-the-Code/python) + +> Talk is cheap. Show me the code.--Linus Torvalds + +---------- + +**第 0000 题:**将你的 QQ 头像(或者微博头像)右上角加上红色的数字,类似于微信未读信息数量那种提示效果。 +类似于图中效果 + +![头像](http://i.imgur.com/sg2dkuY.png?1) + +**第 0001 题:**做为 Apple Store App 独立开发者,你要搞限时促销,为你的应用**生成激活码**(或者优惠券),使用 Python 如何生成 200 个激活码(或者优惠券)? + +**第 0002 题**:将 0001 题生成的 200 个激活码(或者优惠券)保存到 **MySQL** 关系型数据库中。 + +**第 0003 题:**将 0001 题生成的 200 个激活码(或者优惠券)保存到 **Redis** 非关系型数据库中。 + +**第 0004 题:**任一个英文的纯文本文件,统计其中的单词出现的个数。 + +**第 0005 题:**你有一个目录,装了很多照片,把它们的尺寸变成都不大于 iPhone5 分辨率的大小。 + +**第 0006 题:**你有一个目录,放了你一个月的日记,都是 txt,为了避免分词的问题,假设内容都是英文,请统计出你认为每篇日记最重要的词。 + +**第 0007 题:**有个目录,里面是你自己写过的程序,统计一下你写过多少行代码。包括空行和注释,但是要分别列出来。 + +**第 0008 题:**一个HTML文件,找出里面的**正文**。 + +**第 0009 题:**一个HTML文件,找出里面的**链接**。 + +**第 0010 题:**使用 Python 生成类似于下图中的**字母验证码图片** + +![字母验证码](http://i.imgur.com/aVhbegV.jpg) + +- [阅读资料](http://stackoverflow.com/questions/2823316/generate-a-random-letter-in-python) + +**第 0011 题:** 敏感词文本文件 filtered_words.txt,里面的内容为以下内容,当用户输入敏感词语时,则打印出 Freedom,否则打印出 Human Rights。 + + 北京 + 程序员 + 公务员 + 领导 + 牛比 + 牛逼 + 你娘 + 你妈 + love + sex + jiangge + +**第 0012 题:** 敏感词文本文件 filtered_words.txt,里面的内容 和 0011题一样,当用户输入敏感词语,则用 星号 * 替换,例如当用户输入「北京是个好城市」,则变成「**是个好城市」。 + +**第 0013 题:** 用 Python 写一个爬图片的程序,爬 [这个链接里的日本妹子图片 :-)](http://tieba.baidu.com/p/2166231880) + +- [参考代码](http://www.v2ex.com/t/61686 "参考代码") + +**第 0014 题:** 纯文本文件 student.txt为学生信息, 里面的内容(包括花括号)如下所示: + + { + "1":["张三",150,120,100], + "2":["李四",90,99,95], + "3":["王五",60,66,68] + } + +请将上述内容写到 student.xls 文件中,如下图所示: + +![student.xls](http://i.imgur.com/nPDlpme.jpg) + +- [阅读资料](http://www.cnblogs.com/skynet/archive/2013/05/06/3063245.html) 腾讯游戏开发 XML 和 Excel 内容相互转换 + +**第 0015 题:** 纯文本文件 city.txt为城市信息, 里面的内容(包括花括号)如下所示: + + { + "1" : "上海", + "2" : "北京", + "3" : "成都" + } + +请将上述内容写到 city.xls 文件中,如下图所示: + +![city.xls](http://i.imgur.com/rOHbUzg.png) + + +**第 0016 题:** 纯文本文件 numbers.txt, 里面的内容(包括方括号)如下所示: + + [ + [1, 82, 65535], + [20, 90, 13], + [26, 809, 1024] + ] + +请将上述内容写到 numbers.xls 文件中,如下图所示: + +![numbers.xls](http://i.imgur.com/iuz0Pbv.png) + +**第 0017 题:** 将 第 0014 题中的 student.xls 文件中的内容写到 student.xml 文件中,如 + +下所示: + + + + + + { + "1" : ["张三", 150, 120, 100], + "2" : ["李四", 90, 99, 95], + "3" : ["王五", 60, 66, 68] + } + + + +- [阅读资料](http://www.cnblogs.com/skynet/archive/2013/05/06/3063245.html) 腾讯游戏开发 xml 和 Excel 相互转换 + +**第 0018 题:** 将 第 0015 题中的 city.xls 文件中的内容写到 city.xml 文件中,如下所示: + + + + + + { + "1" : "上海", + "2" : "北京", + "3" : "成都" + } + + + +**第 0019 题:** 将 第 0016 题中的 numbers.xls 文件中的内容写到 numbers.xml 文件中,如下 + +所示: + + + + + + + [ + [1, 82, 65535], + [20, 90, 13], + [26, 809, 1024] + ] + + + + +**第 0020 题:** [登陆中国联通网上营业厅](http://iservice.10010.com/index_.html) 后选择「自助服务」 --> 「详单查询」,然后选择你要查询的时间段,点击「查询」按钮,查询结果页面的最下方,点击「导出」,就会生成类似于 2014年10月01日~2014年10月31日通话详单.xls 文件。写代码,对每月通话时间做个统计。 + +**第 0021 题:** 通常,登陆某个网站或者 APP,需要使用用户名和密码。密码是如何加密后存储起来的呢?请使用 Python 对密码加密。 + +- 阅读资料 [用户密码的存储与 Python 示例](http://zhuoqiang.me/password-storage-and-python-example.html) + +- 阅读资料 [Hashing Strings with Python](http://www.pythoncentral.io/hashing-strings-with-python/) + +- 阅读资料 [Python's safest method to store and retrieve passwords from a database](http://stackoverflow.com/questions/2572099/pythons-safest-method-to-store-and-retrieve-passwords-from-a-database) + +**第 0022 题:** iPhone 6、iPhone 6 Plus 早已上市开卖。请查看你写得 第 0005 题的代码是否可以复用。 + +**第 0023 题:** 使用 Python 的 Web 框架,做一个 Web 版本 留言簿 应用。 + +[阅读资料:Python 有哪些 Web 框架](http://v2ex.com/t/151643#reply53) + +- ![留言簿参考](http://i.imgur.com/VIyCZ0i.jpg) + + +**第 0024 题:** 使用 Python 的 Web 框架,做一个 Web 版本 TodoList 应用。 + +- ![SpringSide 版TodoList](http://i.imgur.com/NEf7zHp.jpg) + +**第 0025 题:** 使用 Python 实现:对着电脑吼一声,自动打开浏览器中的默认网站。 + + + 例如,对着笔记本电脑吼一声“百度”,浏览器自动打开百度首页。 + + 关键字:Speech to Text + +参考思路: +1:获取电脑录音-->WAV文件 + python record wav + +2:录音文件-->文本 + + STT: Speech to Text + + STT API Google API + +3:文本-->电脑命令 diff --git a/LXFY/0000/main.py b/LXFY/0000/main.py new file mode 100644 index 00000000..3d758db0 --- /dev/null +++ b/LXFY/0000/main.py @@ -0,0 +1,10 @@ +from PIL import Image, ImageDraw, ImageFont + +def add_num(filePath, num=1): + img = Image.open(filePath) + size = img.size + fontsize = size[1]/4 + myfont = ImageFont.truetype('Futura.ttf', fontsize) + ImageDraw.Draw(img).text((2 * fontsize, 0), str(num), font = myfont, fill = 'red') + img.save('avatar_added.jpg') + img.show() \ No newline at end of file diff --git a/LXFY/0001/main.py b/LXFY/0001/main.py new file mode 100644 index 00000000..19e2cc00 --- /dev/null +++ b/LXFY/0001/main.py @@ -0,0 +1,8 @@ +import random, string + +f = open('Promo_code.txt', 'wb') +for i in range(200): + chars = string.letters + string.digits + s = [random.choice(chars) for i in range(10)] + f.write(''.join(s) + '\n') +f.close() \ No newline at end of file diff --git a/LiamHuang/0000/solution.py b/LiamHuang/0000/solution.py new file mode 100644 index 00000000..b9d119bc --- /dev/null +++ b/LiamHuang/0000/solution.py @@ -0,0 +1,27 @@ +# coding: utf-8 +""" +0000: +将你的 QQ 头像(或者微博头像)右上角加上红色的数字,类似于微信未读信息数量那种提示效果。 +类似于图中效果 http://i.imgur.com/sg2dkuY.png?1 + +笔记参见: +http://liam0205.me/2015/04/22/pil-tutorial-basic-usage/ +http://liam0205.me/2015/05/05/pil-tutorial-imagedraw-and-imagefont/ +""" + +from PIL import Image, ImageDraw, ImageFont + +sourceFileName = "../public/source.png" +avatar = Image.open(sourceFileName) +drawAvatar = ImageDraw.Draw(avatar) + +xSize, ySize = avatar.size +fontSize = min(xSize, ySize) // 11 + +myFont = ImageFont.truetype("/Library/Fonts/OsakaMono.ttf", fontSize) + +drawAvatar.text([0.9 * xSize, 0.1 * ySize - fontSize],\ + "3", fill = (255, 0, 0), font = myFont) +del drawAvatar + +avatar.show() diff --git a/LiamHuang/0001/solution.py b/LiamHuang/0001/solution.py new file mode 100644 index 00000000..e8c6f6d3 --- /dev/null +++ b/LiamHuang/0001/solution.py @@ -0,0 +1,50 @@ +# coding: utf-8 + +''' +做为 Apple Store App 独立开发者,你要搞限时促销,为你的应用生成激活码(或者优惠券), +使用 Python 如何生成 200 个激活码(或者优惠券)? + +笔记参见: +http://liam0205.me/2015/05/07/generator-of-invitation-code-in-python/ +''' + +import random, string + +class LengthError(ValueError): + def __init__(self, arg): + self.args = arg + +def pad_zero_to_left(inputNumString, totalLength): + ''' + takes inputNumString as input, + pads zero to its left, and make it has the length totalLength + 1. calculates the length of inputNumString + 2. compares the length and totalLength + 2.1 if length > totalLength, raise an error + 2.2 if length == totalLength, return directly + 2.3 if length < totalLength, pads zeros to its left + ''' + lengthOfInput = len(inputNumString) + if lengthOfInput > totalLength: + raise LengthError("The length of input is greater than the total\ length.") + else: + return '0' * (totalLength - lengthOfInput) + inputNumString + +poolOfChars = string.ascii_letters + string.digits +random_codes = lambda x, y: ''.join([random.choice(x) for i in range(y)]) + +def invitation_code_generator(quantity, lengthOfRandom, LengthOfKey): + ''' + generate `quantity` invitation codes + ''' + placeHoldChar = "L" + for index in range(quantity): + tempString = "" + try: + yield random_codes(poolOfChars, lengthOfRandom) + placeHoldChar + \ + pad_zero_to_left(str(index), LengthOfKey) + except LengthError: + print "Index exceeds the length of master key." + +for invitationCode in invitation_code_generator(200, 16, 4): + print invitationCode diff --git a/LiamHuang/public/source.png b/LiamHuang/public/source.png new file mode 100644 index 00000000..6190cba0 Binary files /dev/null and b/LiamHuang/public/source.png differ diff --git a/Liez-python-code/0000/0000.py b/Liez-python-code/0000/0000.py new file mode 100644 index 00000000..2a50df6c --- /dev/null +++ b/Liez-python-code/0000/0000.py @@ -0,0 +1,12 @@ + +from PIL import Image, ImageDraw, ImageFont + +def add_num(): + im = Image.open('in.jpg') + xsize, ysize = im.size + draw = ImageDraw.Draw(im) + font = ImageFont.truetype("arial.ttf", xsize // 3) + draw.text((ysize // 5 * 4, 0), '3', (250,128,114), font) + im.save('out.jpg') + +add_num() diff --git a/Liez-python-code/0000/in.jpg b/Liez-python-code/0000/in.jpg new file mode 100644 index 00000000..fa1e6b65 Binary files /dev/null and b/Liez-python-code/0000/in.jpg differ diff --git a/Liez-python-code/0000/out.jpg b/Liez-python-code/0000/out.jpg new file mode 100644 index 00000000..b655421e Binary files /dev/null and b/Liez-python-code/0000/out.jpg differ diff --git a/Liez-python-code/0001/0001.py b/Liez-python-code/0001/0001.py new file mode 100644 index 00000000..6b291859 --- /dev/null +++ b/Liez-python-code/0001/0001.py @@ -0,0 +1,20 @@ + +# coding = utf-8 +__author__= 'liez' + +import random + +def make_number(num, length): + str = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789' + a = [] + i = 0 + while i < num: + numstr = '' + for j in range(length): + numstr += random.choice(str) + if numstr not in a: #如果没重复 + a.append(numstr) + i += 1 + print(numstr) + +make_number(20,10) diff --git a/Liez-python-code/0001/output_sample b/Liez-python-code/0001/output_sample new file mode 100644 index 00000000..2b6dbdce --- /dev/null +++ b/Liez-python-code/0001/output_sample @@ -0,0 +1,22 @@ +COsSx9umWf +QKMSbDVj0G +ARdycodYAf +f8h0drSHJl +e0T6lF6aO1 +ZB06xAlSnf +SmcAqxYHqm +209me2lsCl +NnvmMeMgqd +FqxLZVlzpC +dj7luHI53s +RytNv7yhTH +bg7PDFmGE1 +I7r7S1mpWK +agN2PYF3TI +523YX6TdS8 +GmffcmyoYX +MmZZ2pHieO +gaHTmOVPDT +6rgb3v2TJP + + diff --git a/Liez-python-code/0002/0002.py b/Liez-python-code/0002/0002.py new file mode 100644 index 00000000..a32ef373 --- /dev/null +++ b/Liez-python-code/0002/0002.py @@ -0,0 +1,35 @@ +# coding = utf-8 +__author__= 'liez' + +import random +import sqlite3 + +def make_number(num, length): + str = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789' + a = [] + i = 0 + while i < num: + numstr = '' + for j in range(length): + numstr += random.choice(str) + if numstr not in a: #如果没重复 + a.append(numstr) + i += 1 + print(a) + return a + +def save(a): + try: + connect = sqlite3.connect('codelist.db') + except: + print("failed") + cur = connect.cursor() + cur.execute('create table if not exists codes(code char(20) primary key)') + for item in a: + cur.execute('insert into codes values (?)', [item]) + print("success") + connect.commit() + cur.close() + connect.close() + +save(make_number(20, 10)) diff --git a/Liez-python-code/0004/0004.py b/Liez-python-code/0004/0004.py new file mode 100644 index 00000000..82343bd6 --- /dev/null +++ b/Liez-python-code/0004/0004.py @@ -0,0 +1,20 @@ +# coding = utf-8 +__author__= 'liez' + +import re +def num(path): + with open(path, 'r') as file: + data=file.read() + print(data) + words=re.compile('[a-zA-Z0-9]+') #compile好像是必须用的,用来格式转换什么的,然后才能进行匹配之类的操作 + dict={} + + for x in words.findall(data): + if x not in dict: + dict[x]=1 + else: + dict[x]+=1 + + print(dict) + +num('liez.txt') diff --git a/Liez-python-code/0004/output_sample b/Liez-python-code/0004/output_sample new file mode 100644 index 00000000..0b56d90a --- /dev/null +++ b/Liez-python-code/0004/output_sample @@ -0,0 +1,5 @@ +I am liez. +I am a player. +I love programming. +{'love': 1, 'I': 3, 'player': 1, 'programming': 1, 'a': 1, 'am': 2, 'liez': 1} + diff --git a/Liez-python-code/0005/0005.py b/Liez-python-code/0005/0005.py new file mode 100644 index 00000000..de9c299b --- /dev/null +++ b/Liez-python-code/0005/0005.py @@ -0,0 +1,22 @@ +from PIL import Image +import glob, os + +def resize(): + for files in glob.glob('*.jpg'): + filepath,filename = os.path.split(files) #分割文件名和路径名 + fname,fext = os.path.splitext(filename) + im = Image.open(files) + w,h = im.size + if w > 640: + x = w/640.0 + w = 640 + h = int(h/x) + if h>1136: + x = h/1136.0 + h = 1136 + w = int(w/x) + print(w, h) + im0 = im.resize((w,h),Image.ANTIALIAS) + im0.save('0005'+filename) + +resize() diff --git a/Liez-python-code/0010/0010.py b/Liez-python-code/0010/0010.py new file mode 100644 index 00000000..4348cf3f --- /dev/null +++ b/Liez-python-code/0010/0010.py @@ -0,0 +1,35 @@ +# codeing: utf-8 + +from PIL import Image, ImageDraw, ImageFont, ImageFilter +import string +import random + + +def get4char(): + return [random.choice(string.ascii_letters) for _ in range(4)] # 可以把‘_’换做任意字母,‘_’说明后续不用 + + +def getcolor(): + return random.randint(30, 100), random.randint(30, 100), random.randint(30, 100) + + +def getpicture(): + width = 240 + height = 60 + + image = Image.new('RGB', (width, height), (180, 180, 180)) + font = ImageFont.truetype('arial.ttf', 40) + + draw = ImageDraw.Draw(image) + code = get4char() + for ch in range(4): + draw.text((60 * ch,30), code[ch], font=font, fill=getcolor()) + + for _ in range(random.randint(1500, 3000)): + draw.point((random.randint(0, width), random.randint(0, height)), fill=getcolor()) + + image = image.filter(ImageFilter.BLUR) + image.save("".join(code) + '.jpg') + + +getpicture() diff --git a/Liez-python-code/0010/sample1.jpg b/Liez-python-code/0010/sample1.jpg new file mode 100644 index 00000000..efacef3e Binary files /dev/null and b/Liez-python-code/0010/sample1.jpg differ diff --git a/Liez-python-code/0010/sample2.jpg b/Liez-python-code/0010/sample2.jpg new file mode 100644 index 00000000..533a0bc2 Binary files /dev/null and b/Liez-python-code/0010/sample2.jpg differ diff --git a/Liez-python-code/0010/sample3.jpg b/Liez-python-code/0010/sample3.jpg new file mode 100644 index 00000000..31db9b25 Binary files /dev/null and b/Liez-python-code/0010/sample3.jpg differ diff --git a/Liez-python-code/0011/0011.py b/Liez-python-code/0011/0011.py new file mode 100644 index 00000000..b28411b8 --- /dev/null +++ b/Liez-python-code/0011/0011.py @@ -0,0 +1,13 @@ +def filterwords(x): + with open(x, 'r') as f: + text = f.read() + print (text.split('\n')) + userinput = input('myinput:') + for i in text.split('\n'): + if i in userinput: + return True + +if filterwords('word.txt'): + print ('freedom') +else: + print ('human rights') diff --git a/Liez-python-code/0011/word.txt b/Liez-python-code/0011/word.txt new file mode 100644 index 00000000..1b4f2244 --- /dev/null +++ b/Liez-python-code/0011/word.txt @@ -0,0 +1,11 @@ +北京 +程序员 +公务员 +领导 +牛比 +牛逼 +你娘 +你妈 +love +sex +jiangge diff --git a/Liez-python-code/0012/0012.py b/Liez-python-code/0012/0012.py new file mode 100644 index 00000000..4e84ff77 --- /dev/null +++ b/Liez-python-code/0012/0012.py @@ -0,0 +1,10 @@ +def filtertext(x): + with open(x, 'r') as f: + text = f.read() + userinput = input('myinput:') + for i in text.split('\n'): + if i in userinput: + userinput = userinput.replace(str(i), '*'*len(i)) + print(userinput) + +filtertext('word.txt') diff --git a/Liez-python-code/0012/output b/Liez-python-code/0012/output new file mode 100644 index 00000000..ed45162c --- /dev/null +++ b/Liez-python-code/0012/output @@ -0,0 +1,2 @@ +myinput:我是住在北京的程序员。 +我是住在**的***。 diff --git a/Liez-python-code/0013/0013.py b/Liez-python-code/0013/0013.py new file mode 100644 index 00000000..d339f9e9 --- /dev/null +++ b/Liez-python-code/0013/0013.py @@ -0,0 +1,19 @@ +# 网址:http://tieba.baidu.com/p/4341640851 + +import os +import re +import urllib.request + +def pic_collector(url): + content = urllib.request.urlopen(url).read() + r = re.compile('= 60): + t = sec / 60 + sec = sec % 60 + min = min + t + print("通话时长:%d分%d秒"%(min,sec)) + + #三月日通话次数统计图 + plt.plot(dates, daytimes) + grid(True) + title("Call Times Every Day") + plt.show() + + #根据被叫主叫次数作饼状图 + figure(2, figsize=(6,6)) + fracs = [call/total, becall/total] # 饼状图按被叫和主叫分成两部分的比例 + labels = 'Call', 'Becall' + pie(fracs, labels=labels, autopct='%1.1f%%', shadow=True, startangle=90, colors = ("b", "y")) + title("Call & Becall") + show() + + +get_xls_data("comu.xls") diff --git a/Liez-python-code/Liez b/Liez-python-code/Liez new file mode 100644 index 00000000..f15a4f93 --- /dev/null +++ b/Liez-python-code/Liez @@ -0,0 +1 @@ +Liez is a beginner on Python✧◝(⁰▿⁰)◜✧ diff --git a/MarzinZ/0000/add_num.py b/MarzinZ/0000/add_num.py new file mode 100644 index 00000000..3386fa23 --- /dev/null +++ b/MarzinZ/0000/add_num.py @@ -0,0 +1,18 @@ +from PIL import Image, ImageDraw, ImageFont + +def add_num_to_img(image_path, sign="42"): + im = Image.open(image_path) + width, height = im.size + + draw = ImageDraw.Draw(im) + font = ImageFont.truetype("arial.ttf", min(width//6, height//6)) + draw.text((width*0.75, height*0.075), sign, font=font, fill=(255,33,33, 255)) + + left, right = image_path.rsplit(".", 1) + new_image_path = left + "_" + sign + "." + right + im.save(new_image_path) + +if __name__ == '__main__': + # for test + add_num_to_img("./sample.jpg") + print "Finished." diff --git a/Matafight/0001/gencodes.txt b/Matafight/0001/gencodes.txt new file mode 100644 index 00000000..045129fd --- /dev/null +++ b/Matafight/0001/gencodes.txt @@ -0,0 +1,200 @@ +19a86eae-e274-11e4-a462-b870f41f9997 +19ab06c0-e274-11e4-90b2-b870f41f9997 +19ab06c1-e274-11e4-92e6-b870f41f9997 +19ab06c2-e274-11e4-af0d-b870f41f9997 +19ab06c3-e274-11e4-9ee8-b870f41f9997 +19ab06c4-e274-11e4-bdba-b870f41f9997 +19ab06c5-e274-11e4-98bd-b870f41f9997 +19ab06c6-e274-11e4-9247-b870f41f9997 +19ab06c7-e274-11e4-b1d7-b870f41f9997 +19ab06c8-e274-11e4-9b50-b870f41f9997 +19ab06c9-e274-11e4-b95e-b870f41f9997 +19ab06ca-e274-11e4-a6bc-b870f41f9997 +19ab06cb-e274-11e4-acb2-b870f41f9997 +19ab06cc-e274-11e4-adc3-b870f41f9997 +19ab06cd-e274-11e4-82d2-b870f41f9997 +19ab06ce-e274-11e4-9c5c-b870f41f9997 +19ab06cf-e274-11e4-887b-b870f41f9997 +19ab06d0-e274-11e4-9ae6-b870f41f9997 +19ab06d1-e274-11e4-9a89-b870f41f9997 +19ab06d2-e274-11e4-adc9-b870f41f9997 +19ab06d3-e274-11e4-9717-b870f41f9997 +19ab06d4-e274-11e4-b475-b870f41f9997 +19ab06d5-e274-11e4-971e-b870f41f9997 +19ab06d6-e274-11e4-8726-b870f41f9997 +19ab06d7-e274-11e4-bc47-b870f41f9997 +19ab06d8-e274-11e4-91a3-b870f41f9997 +19ab06d9-e274-11e4-85fe-b870f41f9997 +19ab06da-e274-11e4-b7e9-b870f41f9997 +19ab06db-e274-11e4-8f0d-b870f41f9997 +19ab06dc-e274-11e4-bd0d-b870f41f9997 +19ab06dd-e274-11e4-bb78-b870f41f9997 +19ab06de-e274-11e4-a8cd-b870f41f9997 +19ab06df-e274-11e4-932c-b870f41f9997 +19ab2dcf-e274-11e4-8c44-b870f41f9997 +19ab2dd0-e274-11e4-a7fb-b870f41f9997 +19ab2dd1-e274-11e4-9805-b870f41f9997 +19ab2dd2-e274-11e4-9f0f-b870f41f9997 +19ab2dd3-e274-11e4-b0d7-b870f41f9997 +19ab2dd4-e274-11e4-9ab0-b870f41f9997 +19ab2dd5-e274-11e4-b7e0-b870f41f9997 +19ab2dd6-e274-11e4-9e9f-b870f41f9997 +19ab2dd7-e274-11e4-9b23-b870f41f9997 +19ab2dd8-e274-11e4-af20-b870f41f9997 +19ab2dd9-e274-11e4-893b-b870f41f9997 +19ab2dda-e274-11e4-ae1f-b870f41f9997 +19ab2ddb-e274-11e4-83ba-b870f41f9997 +19ab2ddc-e274-11e4-9f4d-b870f41f9997 +19ab2ddd-e274-11e4-abca-b870f41f9997 +19ab2dde-e274-11e4-8e66-b870f41f9997 +19ab2ddf-e274-11e4-9ef6-b870f41f9997 +19ab2de0-e274-11e4-bc9f-b870f41f9997 +19ab2de1-e274-11e4-aad4-b870f41f9997 +19ab2de2-e274-11e4-8b72-b870f41f9997 +19ab2de3-e274-11e4-8fb4-b870f41f9997 +19ab2de4-e274-11e4-b16e-b870f41f9997 +19ab2de5-e274-11e4-9c55-b870f41f9997 +19ab2de6-e274-11e4-8944-b870f41f9997 +19ab2de7-e274-11e4-a194-b870f41f9997 +19ab2de8-e274-11e4-939a-b870f41f9997 +19ab2de9-e274-11e4-9407-b870f41f9997 +19ab2dea-e274-11e4-89dd-b870f41f9997 +19ab2deb-e274-11e4-ab68-b870f41f9997 +19ab2dec-e274-11e4-81c4-b870f41f9997 +19ab2ded-e274-11e4-8a0a-b870f41f9997 +19ab2dee-e274-11e4-b053-b870f41f9997 +19ab2def-e274-11e4-b9eb-b870f41f9997 +19ab2df0-e274-11e4-b4c4-b870f41f9997 +19ab2df1-e274-11e4-bb71-b870f41f9997 +19ab2df2-e274-11e4-866d-b870f41f9997 +19ab2df3-e274-11e4-a075-b870f41f9997 +19ab2df4-e274-11e4-a26d-b870f41f9997 +19ab2df5-e274-11e4-97e7-b870f41f9997 +19ab2df6-e274-11e4-8daf-b870f41f9997 +19ab2df7-e274-11e4-8454-b870f41f9997 +19ab2df8-e274-11e4-846f-b870f41f9997 +19ab2df9-e274-11e4-bbcf-b870f41f9997 +19ab2dfa-e274-11e4-8c00-b870f41f9997 +19ab2dfb-e274-11e4-9dfd-b870f41f9997 +19ab2dfc-e274-11e4-bc23-b870f41f9997 +19ab2dfd-e274-11e4-bc22-b870f41f9997 +19ab2dfe-e274-11e4-aeb7-b870f41f9997 +19ab2dff-e274-11e4-a089-b870f41f9997 +19ab54de-e274-11e4-bbae-b870f41f9997 +19ab54df-e274-11e4-9bcc-b870f41f9997 +19ab54e0-e274-11e4-b29f-b870f41f9997 +19ab54e1-e274-11e4-b35e-b870f41f9997 +19ab54e2-e274-11e4-a961-b870f41f9997 +19ab54e3-e274-11e4-b4ac-b870f41f9997 +19ab54e4-e274-11e4-92f1-b870f41f9997 +19ab54e5-e274-11e4-9e32-b870f41f9997 +19ab54e6-e274-11e4-81c6-b870f41f9997 +19ab54e7-e274-11e4-8ddf-b870f41f9997 +19ab54e8-e274-11e4-80a2-b870f41f9997 +19ab54e9-e274-11e4-a464-b870f41f9997 +19ab54ea-e274-11e4-82a3-b870f41f9997 +19ab54eb-e274-11e4-8063-b870f41f9997 +19ab54ec-e274-11e4-a971-b870f41f9997 +19ab54ed-e274-11e4-ae75-b870f41f9997 +19ab54ee-e274-11e4-b3eb-b870f41f9997 +19ab54ef-e274-11e4-a18f-b870f41f9997 +19ab54f0-e274-11e4-8caa-b870f41f9997 +19ab54f1-e274-11e4-b8c5-b870f41f9997 +19ab54f2-e274-11e4-8a9e-b870f41f9997 +19ab54f3-e274-11e4-95ee-b870f41f9997 +19ab54f4-e274-11e4-88e3-b870f41f9997 +19ab54f5-e274-11e4-bf12-b870f41f9997 +19ab54f6-e274-11e4-ada4-b870f41f9997 +19ab54f7-e274-11e4-b0ef-b870f41f9997 +19ab54f8-e274-11e4-8b9a-b870f41f9997 +19ab54f9-e274-11e4-98b1-b870f41f9997 +19ab54fa-e274-11e4-916d-b870f41f9997 +19ab54fb-e274-11e4-8ec0-b870f41f9997 +19ab54fc-e274-11e4-b626-b870f41f9997 +19ab54fd-e274-11e4-a904-b870f41f9997 +19ab54fe-e274-11e4-8662-b870f41f9997 +19ab54ff-e274-11e4-83d1-b870f41f9997 +19ab5500-e274-11e4-9042-b870f41f9997 +19ab5501-e274-11e4-b901-b870f41f9997 +19ab5502-e274-11e4-bcfa-b870f41f9997 +19ab5503-e274-11e4-8736-b870f41f9997 +19ab5504-e274-11e4-86f5-b870f41f9997 +19ab5505-e274-11e4-93bc-b870f41f9997 +19ab5506-e274-11e4-830d-b870f41f9997 +19ab5507-e274-11e4-b3f1-b870f41f9997 +19ab5508-e274-11e4-93d5-b870f41f9997 +19ab5509-e274-11e4-923a-b870f41f9997 +19ab550a-e274-11e4-85a4-b870f41f9997 +19ab550b-e274-11e4-9502-b870f41f9997 +19ab550c-e274-11e4-b9f6-b870f41f9997 +19ab550d-e274-11e4-a867-b870f41f9997 +19ab550e-e274-11e4-89ae-b870f41f9997 +19ab550f-e274-11e4-8ae9-b870f41f9997 +19ab5510-e274-11e4-885e-b870f41f9997 +19ab5511-e274-11e4-90f8-b870f41f9997 +19ab7bee-e274-11e4-9370-b870f41f9997 +19ab7bef-e274-11e4-846a-b870f41f9997 +19ab7bf0-e274-11e4-839f-b870f41f9997 +19ab7bf1-e274-11e4-a17d-b870f41f9997 +19ab7bf2-e274-11e4-8619-b870f41f9997 +19ab7bf3-e274-11e4-a290-b870f41f9997 +19ab7bf4-e274-11e4-89c3-b870f41f9997 +19ab7bf5-e274-11e4-ad3b-b870f41f9997 +19ab7bf6-e274-11e4-ae67-b870f41f9997 +19ab7bf7-e274-11e4-938b-b870f41f9997 +19ab7bf8-e274-11e4-a6e5-b870f41f9997 +19ab7bf9-e274-11e4-805e-b870f41f9997 +19ab7bfa-e274-11e4-a574-b870f41f9997 +19ab7bfb-e274-11e4-a379-b870f41f9997 +19ab7bfc-e274-11e4-873c-b870f41f9997 +19ab7bfd-e274-11e4-a312-b870f41f9997 +19ab7bfe-e274-11e4-88f3-b870f41f9997 +19ab7bff-e274-11e4-98bf-b870f41f9997 +19ab7c00-e274-11e4-854c-b870f41f9997 +19ab7c01-e274-11e4-aefa-b870f41f9997 +19ab7c02-e274-11e4-96aa-b870f41f9997 +19ab7c03-e274-11e4-bea1-b870f41f9997 +19ab7c04-e274-11e4-ade7-b870f41f9997 +19ab7c05-e274-11e4-8f69-b870f41f9997 +19ab7c06-e274-11e4-9f5c-b870f41f9997 +19ab7c07-e274-11e4-b7b5-b870f41f9997 +19ab7c08-e274-11e4-b981-b870f41f9997 +19ab7c09-e274-11e4-9afa-b870f41f9997 +19ab7c0a-e274-11e4-bfb1-b870f41f9997 +19ab7c0b-e274-11e4-82d7-b870f41f9997 +19ab7c0c-e274-11e4-b270-b870f41f9997 +19ab7c0d-e274-11e4-bae6-b870f41f9997 +19ab7c0e-e274-11e4-8b31-b870f41f9997 +19ab7c0f-e274-11e4-8cde-b870f41f9997 +19ab7c10-e274-11e4-a381-b870f41f9997 +19ab7c11-e274-11e4-8716-b870f41f9997 +19ab7c12-e274-11e4-8884-b870f41f9997 +19ab7c13-e274-11e4-80ff-b870f41f9997 +19ab7c14-e274-11e4-acc5-b870f41f9997 +19ab7c15-e274-11e4-a471-b870f41f9997 +19aba300-e274-11e4-8f8f-b870f41f9997 +19aba301-e274-11e4-a482-b870f41f9997 +19aba302-e274-11e4-9d99-b870f41f9997 +19aba303-e274-11e4-912e-b870f41f9997 +19aba304-e274-11e4-8850-b870f41f9997 +19aba305-e274-11e4-8c3b-b870f41f9997 +19aba306-e274-11e4-aab1-b870f41f9997 +19aba307-e274-11e4-9eef-b870f41f9997 +19aba308-e274-11e4-bb0f-b870f41f9997 +19aba309-e274-11e4-9209-b870f41f9997 +19aba30a-e274-11e4-90fc-b870f41f9997 +19aba30b-e274-11e4-b358-b870f41f9997 +19aba30c-e274-11e4-a370-b870f41f9997 +19aba30d-e274-11e4-8500-b870f41f9997 +19aba30e-e274-11e4-9f97-b870f41f9997 +19aba30f-e274-11e4-bd2f-b870f41f9997 +19aba310-e274-11e4-aac0-b870f41f9997 +19aba311-e274-11e4-b0f9-b870f41f9997 +19aba312-e274-11e4-ac67-b870f41f9997 +19aba313-e274-11e4-957e-b870f41f9997 +19aba314-e274-11e4-9150-b870f41f9997 +19aba315-e274-11e4-8e0d-b870f41f9997 +19aba316-e274-11e4-a72e-b870f41f9997 +19aba317-e274-11e4-ae22-b870f41f9997 +19aba318-e274-11e4-8f40-b870f41f9997 +19aba319-e274-11e4-85be-b870f41f9997 diff --git a/Matafight/0001/generate_200.py b/Matafight/0001/generate_200.py new file mode 100644 index 00000000..6cb7305e --- /dev/null +++ b/Matafight/0001/generate_200.py @@ -0,0 +1,23 @@ +#_*_ encoding: utf-8 _*_ +import uuid + +class generate: + def __init__(self): + self.num=0; + self.listid=[]; + def generate_uuid(self,num): + for i in range(int(num)): + self.listid.append(uuid.uuid1()); + + def get_uuid(self): + return self.listid; + +if __name__=="__main__": + gencode=generate(); + gencode.generate_uuid(200); + keys=gencode.get_uuid(); + filekeys=file("gencodes.txt",'w'); + for key in keys: + filekeys.write(str(key)+'\n'); + filekeys.close(); + diff --git a/Matafight/0004/countWord.py b/Matafight/0004/countWord.py new file mode 100644 index 00000000..3766b9eb --- /dev/null +++ b/Matafight/0004/countWord.py @@ -0,0 +1,10 @@ +#_*_ encoding: utf-8 _*_ +import re + +inputfile=file("test.txt",'r'); +count=0; +for line in inputfile.readlines(): + word=re.findall(r"\w+",line); + count+=len(word); +print "total wordcount is "+ str(count); +inputfile.close(); diff --git a/Matafight/0004/test.txt b/Matafight/0004/test.txt new file mode 100644 index 00000000..3505a728 --- /dev/null +++ b/Matafight/0004/test.txt @@ -0,0 +1,2 @@ +this is a test file +this is second line: \ No newline at end of file diff --git a/Matafight/0006/diary1.txt b/Matafight/0006/diary1.txt new file mode 100644 index 00000000..c6e8552e --- /dev/null +++ b/Matafight/0006/diary1.txt @@ -0,0 +1 @@ +this is a diary test is \ No newline at end of file diff --git a/Matafight/0006/diary2.txt b/Matafight/0006/diary2.txt new file mode 100644 index 00000000..76afcce7 --- /dev/null +++ b/Matafight/0006/diary2.txt @@ -0,0 +1,2 @@ +test +test \ No newline at end of file diff --git a/Matafight/0006/diary3.txt b/Matafight/0006/diary3.txt new file mode 100644 index 00000000..f27296b5 --- /dev/null +++ b/Matafight/0006/diary3.txt @@ -0,0 +1,2 @@ +diary3 +diary3 \ No newline at end of file diff --git a/Matafight/0006/importantdiary.py b/Matafight/0006/importantdiary.py new file mode 100644 index 00000000..f062a504 --- /dev/null +++ b/Matafight/0006/importantdiary.py @@ -0,0 +1,41 @@ +#_*_ encoding: utf-8 _*_ +import re + +class countWord: + def __init__(self): + self.dic={}; + self.word=""; + + + def count(self,filename): + self.dic={}; + fopen=file(filename,'r'); + for lines in fopen.readlines(): + words=re.findall(r"\w+",lines); + for items in words: + if items in self.dic.keys(): + self.dic[items]+=1; + else: + self.dic[items]=1; + + #对字典value值排序 + dict= sorted(self.dic.iteritems(), key=lambda d:d[1], reverse = True); + self.word=dict[0][0]; + + def getWord(self): + return self.word; + + +if __name__=="__main__": + diarycount=countWord(); + order=1; + importantlist=[]; + for order in range(1,4): + fname="diary"+str(order)+".txt"; + diarycount.count(fname); + importantlist.append(diarycount.getWord()); + order+=1; + for item in importantlist: + print str(item)+"\t"; + + diff --git a/Matafight/0007/countCodeLines.py b/Matafight/0007/countCodeLines.py new file mode 100644 index 00000000..e3ca80a0 --- /dev/null +++ b/Matafight/0007/countCodeLines.py @@ -0,0 +1,63 @@ +#_*_ encoding: utf-8 _*_ +import os +import re +#http://www.cnblogs.com/zhoujie/archive/2013/04/10/python7.html +#http://cuiqingcai.com/977.html +class countLines: + def __init__(self): + self.comment=0; + self.codes=0; + self.blank=0; + self.fileList=[];#存的是各个文件相关的list + def openDir(self,dirname): + curdir=os.getcwd(); + curdir=curdir+str(dirname); + print curdir + dirlist=os.listdir(curdir); + checkpy=re.compile(r"\.py$"); + for item in dirlist: + if checkpy.search(item): + item="\\"+item; + self.count(curdir+item); + + def count(self,filename): + self.comment=0; + self.codes=0; + self.blank=0; + f=file(filename,'r'); + patcomment=re.compile(r"^\s*#");# + patblank=re.compile(r"^\s+$");#空白字符 + for line in f.readlines(): + if patblank.search(line): + self.blank+=1; + elif patcomment.search(line): + self.comment+=1; + else: + self.codes+=1; + self.fileList.append([filename,self.codes,self.comment,self.blank]); + + f.close(); + + def getResult(self): + return self.fileList; + +if __name__=="__main__": + countInstance=countLines(); + countInstance.openDir(r"\testDir"); + relist=countInstance.getResult(); + for item in relist: + print item[0]; + print "code num:"+str(item[1]); + print "comment num:"+str(item[2]); + print "blank num:"+str(item[3]); + print "\n" + + + + + + + + + + diff --git a/Matafight/0007/testDir/countWord.py b/Matafight/0007/testDir/countWord.py new file mode 100644 index 00000000..3766b9eb --- /dev/null +++ b/Matafight/0007/testDir/countWord.py @@ -0,0 +1,10 @@ +#_*_ encoding: utf-8 _*_ +import re + +inputfile=file("test.txt",'r'); +count=0; +for line in inputfile.readlines(): + word=re.findall(r"\w+",line); + count+=len(word); +print "total wordcount is "+ str(count); +inputfile.close(); diff --git a/Matafight/0007/testDir/generate_200.py b/Matafight/0007/testDir/generate_200.py new file mode 100644 index 00000000..6cb7305e --- /dev/null +++ b/Matafight/0007/testDir/generate_200.py @@ -0,0 +1,23 @@ +#_*_ encoding: utf-8 _*_ +import uuid + +class generate: + def __init__(self): + self.num=0; + self.listid=[]; + def generate_uuid(self,num): + for i in range(int(num)): + self.listid.append(uuid.uuid1()); + + def get_uuid(self): + return self.listid; + +if __name__=="__main__": + gencode=generate(); + gencode.generate_uuid(200); + keys=gencode.get_uuid(); + filekeys=file("gencodes.txt",'w'); + for key in keys: + filekeys.write(str(key)+'\n'); + filekeys.close(); + diff --git a/Matafight/0007/testDir/importantdiary.py b/Matafight/0007/testDir/importantdiary.py new file mode 100644 index 00000000..f062a504 --- /dev/null +++ b/Matafight/0007/testDir/importantdiary.py @@ -0,0 +1,41 @@ +#_*_ encoding: utf-8 _*_ +import re + +class countWord: + def __init__(self): + self.dic={}; + self.word=""; + + + def count(self,filename): + self.dic={}; + fopen=file(filename,'r'); + for lines in fopen.readlines(): + words=re.findall(r"\w+",lines); + for items in words: + if items in self.dic.keys(): + self.dic[items]+=1; + else: + self.dic[items]=1; + + #对字典value值排序 + dict= sorted(self.dic.iteritems(), key=lambda d:d[1], reverse = True); + self.word=dict[0][0]; + + def getWord(self): + return self.word; + + +if __name__=="__main__": + diarycount=countWord(); + order=1; + importantlist=[]; + for order in range(1,4): + fname="diary"+str(order)+".txt"; + diarycount.count(fname); + importantlist.append(diarycount.getWord()); + order+=1; + for item in importantlist: + print str(item)+"\t"; + + diff --git a/Matafight/0007/testDir/test.txt b/Matafight/0007/testDir/test.txt new file mode 100644 index 00000000..a4c321ec --- /dev/null +++ b/Matafight/0007/testDir/test.txt @@ -0,0 +1,3 @@ +what +# +kiddingme \ No newline at end of file diff --git a/Matafight/0009/getLinks.py b/Matafight/0009/getLinks.py new file mode 100644 index 00000000..df0d3d24 --- /dev/null +++ b/Matafight/0009/getLinks.py @@ -0,0 +1,25 @@ +# _*_ encodeing: utf-8 _*_ +from HTMLParser import HTMLParser +import urllib2 + +class myParser(HTMLParser): + def __init__(self): + HTMLParser.__init__(self); + self.flag=0; + self.links=[]; + + def handle_starttag(self, tag, attrs): + if tag == "a": + for name,value in attrs: + if name =="href": + self.links.append(value); + + +if __name__=="__main__": + parser=myParser(); + myurl='http://www.baidu.com'; + html=urllib2.urlopen(myurl); + htmlcode=html.read(); + parser.feed(htmlcode); + print parser.links; + diff --git a/Matafight/0011/filtered_word.txt b/Matafight/0011/filtered_word.txt new file mode 100644 index 00000000..69373b64 --- /dev/null +++ b/Matafight/0011/filtered_word.txt @@ -0,0 +1,11 @@ +北京 +程序员 +公务员 +领导 +牛比 +牛逼 +你娘 +你妈 +love +sex +jiangge \ No newline at end of file diff --git a/Matafight/0011/senWord.py b/Matafight/0011/senWord.py new file mode 100644 index 00000000..e9f331fb --- /dev/null +++ b/Matafight/0011/senWord.py @@ -0,0 +1,33 @@ +# -*-coding:utf-8-*- +import string + +class senseWord(): + def __init__(self): + self.list=[] + inputfile=file('filtered_word.txt','r') + for lines in inputfile.readlines(): + self.list.append(lines.decode('utf-8').encode('gbk'))#I've set the file coding type as utf-8 + inputfile.close() + self.list=map(string.strip,self.list); + for item in self.list: + print item + def checkWord(self,word): + for words in self.list: + if words == word: + return True + return False + +if __name__=='__main__': + myCheck=senseWord() + ipstr=raw_input() + while True: + ipstr=raw_input() + if ipstr: + if(myCheck.checkWord(ipstr)): + print 'Freedom' + else: + print 'humanRight' + else: + break + + diff --git a/Matafight/0012/ResenWord.py b/Matafight/0012/ResenWord.py new file mode 100644 index 00000000..052716de --- /dev/null +++ b/Matafight/0012/ResenWord.py @@ -0,0 +1,45 @@ +# -*-coding:utf-8-*- +import string +class senseWord(): + def __init__(self): + self.list=[] + self.word=[] + inputfile=file('filtered_word.txt','r') + for lines in inputfile.readlines(): + self.list.append(lines.decode('utf-8').encode('gbk'))#I've set the file coding type as utf-8 + inputfile.close() + self.list=map(string.strip,self.list); + + def checkWord(self,word): + flag=False + for words in self.list: + if words in word: + self.word.append(words) + flag= True + return flag + + def getWord(self): + + return self.word + +if __name__=='__main__': + myCheck=senseWord() + while True: + ipstr=str(raw_input()) + if ipstr: + if(myCheck.checkWord(ipstr)): + senseList=myCheck.getWord() + for items in senseList: + length=len(items.decode('gbk')) + torep='*'; + for i in range(1,length): + torep+='*' + ipstr=ipstr.replace(items,torep) + print ipstr + else: + print ipstr + else: + break + + + diff --git a/Matafight/0012/filtered_word.txt b/Matafight/0012/filtered_word.txt new file mode 100644 index 00000000..69373b64 --- /dev/null +++ b/Matafight/0012/filtered_word.txt @@ -0,0 +1,11 @@ +北京 +程序员 +公务员 +领导 +牛比 +牛逼 +你娘 +你妈 +love +sex +jiangge \ No newline at end of file diff --git a/Mr.Lin/0005/1.jpg b/Mr.Lin/0005/1.jpg deleted file mode 100644 index 4d839820..00000000 Binary files a/Mr.Lin/0005/1.jpg and /dev/null differ diff --git a/Mr.Lin/0005/result-1.jpg b/Mr.Lin/0005/result-1.jpg deleted file mode 100644 index 2b6727c5..00000000 Binary files a/Mr.Lin/0005/result-1.jpg and /dev/null differ diff --git a/NKUCodingCat/0000/img.jpg b/NKUCodingCat/0000/img.jpg deleted file mode 100644 index b2d0fc33..00000000 Binary files a/NKUCodingCat/0000/img.jpg and /dev/null differ diff --git a/NKUCodingCat/0000/res.jpg b/NKUCodingCat/0000/res.jpg deleted file mode 100644 index 748060d1..00000000 Binary files a/NKUCodingCat/0000/res.jpg and /dev/null differ diff --git a/NKUCodingCat/0005/dst_img/1_1600x900.jpg b/NKUCodingCat/0005/dst_img/1_1600x900.jpg deleted file mode 100644 index 1839ff0e..00000000 Binary files a/NKUCodingCat/0005/dst_img/1_1600x900.jpg and /dev/null differ diff --git a/NKUCodingCat/0005/dst_img/2_1600x900 (1).jpg b/NKUCodingCat/0005/dst_img/2_1600x900 (1).jpg deleted file mode 100644 index 9022a808..00000000 Binary files a/NKUCodingCat/0005/dst_img/2_1600x900 (1).jpg and /dev/null differ diff --git a/NKUCodingCat/0005/dst_img/2_1600x900.jpg b/NKUCodingCat/0005/dst_img/2_1600x900.jpg deleted file mode 100644 index fa6ef10b..00000000 Binary files a/NKUCodingCat/0005/dst_img/2_1600x900.jpg and /dev/null differ diff --git a/NKUCodingCat/0005/img/1_1600x900.jpg b/NKUCodingCat/0005/img/1_1600x900.jpg deleted file mode 100644 index 31fd478f..00000000 Binary files a/NKUCodingCat/0005/img/1_1600x900.jpg and /dev/null differ diff --git a/NKUCodingCat/0005/img/2_1600x900 (1).jpg b/NKUCodingCat/0005/img/2_1600x900 (1).jpg deleted file mode 100644 index 2ae772df..00000000 Binary files a/NKUCodingCat/0005/img/2_1600x900 (1).jpg and /dev/null differ diff --git a/NKUCodingCat/0005/img/2_1600x900.jpg b/NKUCodingCat/0005/img/2_1600x900.jpg deleted file mode 100644 index c41bb26a..00000000 Binary files a/NKUCodingCat/0005/img/2_1600x900.jpg and /dev/null differ diff --git a/NKUCodingCat/0010/code.jpg b/NKUCodingCat/0010/code.jpg deleted file mode 100644 index a7a63868..00000000 Binary files a/NKUCodingCat/0010/code.jpg and /dev/null differ diff --git a/NKUCodingCat/0024/0024.sql b/NKUCodingCat/0024/0024.sql deleted file mode 100644 index a07fa402..00000000 --- a/NKUCodingCat/0024/0024.sql +++ /dev/null @@ -1,67 +0,0 @@ -# SQL-Front 5.1 (Build 4.16) - -/*!40101 SET @OLD_SQL_MODE=@@SQL_MODE */; -/*!40101 SET SQL_MODE='NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION' */; -/*!40111 SET @OLD_SQL_NOTES=@@SQL_NOTES */; -/*!40103 SET SQL_NOTES='ON' */; -/*!40014 SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS */; -/*!40014 SET UNIQUE_CHECKS=0 */; -/*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS */; -/*!40014 SET FOREIGN_KEY_CHECKS=0 */; - - -# Host: localhost Database: 0024 -# ------------------------------------------------------ -# Server version 5.5.38 - -DROP DATABASE IF EXISTS `0024`; -CREATE DATABASE `0024` /*!40100 DEFAULT CHARACTER SET utf8 */; -USE `0024`; - -# -# Source for table code -# - -DROP TABLE IF EXISTS `code`; -CREATE TABLE `code` ( - `id` int(20) NOT NULL DEFAULT '0', - `to` text NOT NULL -) ENGINE=MyISAM DEFAULT CHARSET=utf8; - -# -# Dumping data for table code -# - -LOCK TABLES `code` WRITE; -/*!40000 ALTER TABLE `code` DISABLE KEYS */; -INSERT INTO `code` VALUES (13,'haiohpd'); -INSERT INTO `code` VALUES (14,'daduwwg'); -INSERT INTO `code` VALUES (9,'7'); -INSERT INTO `code` VALUES (11,'9'); -/*!40000 ALTER TABLE `code` ENABLE KEYS */; -UNLOCK TABLES; - -# -# Source for table max -# - -DROP TABLE IF EXISTS `max`; -CREATE TABLE `max` ( - `pro` varchar(255) DEFAULT NULL, - `max` int(11) NOT NULL -) ENGINE=MyISAM DEFAULT CHARSET=utf8; - -# -# Dumping data for table max -# - -LOCK TABLES `max` WRITE; -/*!40000 ALTER TABLE `max` DISABLE KEYS */; -INSERT INTO `max` VALUES ('max',15); -/*!40000 ALTER TABLE `max` ENABLE KEYS */; -UNLOCK TABLES; - -/*!40014 SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS */; -/*!40014 SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS */; -/*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */; -/*!40101 SET SQL_MODE=@OLD_SQL_MODE */; diff --git a/NKUCodingCat/0024/SQLIO.py b/NKUCodingCat/0024/SQLIO.py deleted file mode 100644 index 910189d9..00000000 --- a/NKUCodingCat/0024/SQLIO.py +++ /dev/null @@ -1,53 +0,0 @@ -#coding=utf-8 -import time, os, json, MySQLdb, HTMLParser, cgi -def SQL_init(): - db = MySQLdb.connect("127.0.0.1","root","root","0024" ) - return db.cursor() -def SQL_max(new=None): - cursor = SQL_init() - if new != None: - sql="""UPDATE `max` SET `max`=%d WHERE `pro`='max'"""%new - cursor.execute(sql) - return True - else: - sql="""SELECT * FROM `max` WHERE `pro`='max'""" - cursor.execute(sql) - max = cursor.fetchall()[0][1] - SQL_max(max+1) - return max -def SQL_in(task): - max = SQL_max() - cursor = SQL_init() - sql = """INSERT INTO `code` SET `id`=%d,`to`='%s';"""%(max, task) - cursor.execute(sql) - return True -def SQL_out(): - cursor = SQL_init() - sql = """SELECT * FROM `code`""" - cursor.execute(sql) - return cursor.fetchall() -def SQL_del(id): - cursor = SQL_init() - sql = """DELETE FROM `code` WHERE `id`=%d"""%id - cursor.execute(sql) - return json.dumps(cursor.fetchall()) -#----------- -Temp = """ - - %s - -
- -
- -""" - - -def PageMake(): - Data = SQL_out() - All = "" - Data = sorted(Data,key=lambda a:a[0] ) - for i in Data: - #print i - All+=Temp%(str(i[1]),int(i[0])) - return All \ No newline at end of file diff --git a/NKUCodingCat/0024/main.py b/NKUCodingCat/0024/main.py deleted file mode 100644 index ba03e834..00000000 --- a/NKUCodingCat/0024/main.py +++ /dev/null @@ -1,71 +0,0 @@ -#coding=utf-8 -const = """ - - - - - - - - -

TodoList应用演示

- -
- - - - - - - - {0} -
任务
管理
-
- - -
- - - - -""" - - -from bottle import static_file,route, run, post, request, redirect, error -import os, urllib,re,json,time -Root = os.path.split(os.path.realpath(__file__))[0]+"/static/" -import SQLIO - -@route('/todo') -def index(): - return const.format(SQLIO.PageMake(),) -@post('/todo') -def Accept(): - Req = request.body.read() - L = re.split("&",Req) - M = {} - for i in L: - A = re.split("=",i) - M[A[0]] = urllib.unquote(A[1]) - for j in M.keys(): - if re.findall("id-",j): - SQLIO.SQL_del(int(j[3:])) - redirect('/todo', 302) - try: - type = M["new"] - newtask = M["newtask"] - except: - redirect('/error', 404) - if newtask != "": - SQLIO.SQL_in(newtask) - redirect('/todo', 302) - else: - return "=.=所以你想添加什么任务呀" - -@route('/error') -def err(): - return "虽然不知道你在干什么但是触发了服务器错误呢" -@route('/static/') -def server_static(filename): - return static_file(filename, root=Root) -run(host='localhost',port=8080) \ No newline at end of file diff --git a/NKUCodingCat/0024/static/css.css b/NKUCodingCat/0024/static/css.css deleted file mode 100644 index da2076eb..00000000 --- a/NKUCodingCat/0024/static/css.css +++ /dev/null @@ -1 +0,0 @@ -h1{color:green;}table,th,td{border:1px solid blue;}table{border-collapse:collapse;width:100%;}th{height:50px;}td.task{width:70%;}input#delete{font-size:15px;color:blue;background-color:#FFFFFF;border-width:0;cursor:pointer;}textarea{vertical-align:middle;width:500px;height:100px;}input#submit{width:107px;height:42px;border-width:0;font-size:17px;font-weight:500;border-radius:6px;cursor:pointer;} \ No newline at end of file diff --git a/NeilLi1992/0000/main.py b/NeilLi1992/0000/main.py new file mode 100644 index 00000000..0998925c --- /dev/null +++ b/NeilLi1992/0000/main.py @@ -0,0 +1,29 @@ +from PIL import Image +from PIL import ImageFont +from PIL import ImageDraw + +file_name = raw_input("Please input the image name, including file appendix: ") +try: + img = Image.open("test.jpg") + s = raw_input("Please input the number to display: ") + try: + num = int(s) + img_width = img.size[0] + img_height = img.size[1] + + font_size = 60 * img_height / 480 + font_height = 60 + font_width = 40 + text_x = img_width - font_width * len(str(num)) + text_y = 0 + + font = ImageFont.truetype("Arial.ttf", font_size) + + draw = ImageDraw.Draw(img) + draw.text((text_x, text_y), str(num), (255,0,0), font=font) + + img.save("new_image.jpg") + except: + print "The input is not a number!" +except: + print "Can't find specified file!" diff --git a/PyBeaner/0001/coupon.py b/PyBeaner/0001/coupon.py new file mode 100644 index 00000000..460b6182 --- /dev/null +++ b/PyBeaner/0001/coupon.py @@ -0,0 +1,30 @@ +__author__ = 'PyBeaner' +from random import choice +import string + +chars = string.ascii_uppercase + string.digits + + +def generate_coupons(count, coupon_length=5): + coupons = [] + for i in range(count): + coupon = generate_one_coupon(coupon_length=coupon_length) + while coupon in coupons: + coupon = generate_one_coupon(coupon_length) + + coupons.append(coupon) + + return coupons + + +def generate_one_coupon(coupon_length=5): + coupon = [] + for i in range(coupon_length): + ch = choice(chars) + coupon.append(ch) + return "".join(coupon) + + +if __name__ == '__main__': + coupons = generate_coupons(200, 5) + print(coupons) diff --git a/PyBeaner/0002/save_to_mysql.py b/PyBeaner/0002/save_to_mysql.py new file mode 100644 index 00000000..a9a7f9bf --- /dev/null +++ b/PyBeaner/0002/save_to_mysql.py @@ -0,0 +1,26 @@ +__author__ = 'PyBeaner' +import pymysql.cursors + + +def save_to_mysql(coupons): + try: + connection = pymysql.connect(host='localhost', + user='user', + passwd='passwd', + db='db', + cursorclass=pymysql.cursors.DictCursor) + + with connection.cursor() as cursor: + select_sql = "SELECT coupon FROM coupons where coupon='%s'" + insert_sql = "INSERT INTO coupons VALUES (%s);" + for coupon in coupons: + cursor.excute(select_sql, (coupon,)) + result = cursor.fetchone() + if result: + continue + + cursor.excute(insert_sql, (coupon,)) + + connection.commit() + finally: + connection.close() diff --git a/PyBeaner/0004/wc.py b/PyBeaner/0004/wc.py new file mode 100644 index 00000000..8af8b03a --- /dev/null +++ b/PyBeaner/0004/wc.py @@ -0,0 +1,11 @@ +from collections import Counter +import re + +__author__ = "PyBeaner" + +with open(r"F:\Program Files\Git\doc\git\html\RelNotes\1.5.0.1.txt") as f: + word_pat = re.compile("^[A-Za-z]+$") + file_words = [word for line in f for word in line.split() + if len(word) > 1 and word_pat.match(word)] + +print(Counter(file_words)) diff --git a/PyBeaner/0007/code_lines.py b/PyBeaner/0007/code_lines.py new file mode 100644 index 00000000..81484695 --- /dev/null +++ b/PyBeaner/0007/code_lines.py @@ -0,0 +1,43 @@ +# coding=utf-8 +__author__ = 'PyBeaner' +import os +import fnmatch + +total_lines = 0 +code_lines = 0 +empty_lines = 0 +comment_lines = 0 + + +def count_line(line): + line = line.lstrip() + global comment_lines, empty_lines, total_lines, code_lines + + total_lines += 1 + if line.startswith("#"): + comment_lines += 1 + elif not line: + empty_lines += 1 + else: + code_lines += 1 + + +def scan_dir(directory, suffix="*.py"): + directory = os.path.abspath(directory) + print("Scanning files in %s ..." % directory) + for cur_dir, dirs, files in os.walk(directory): + for file in files: + if not fnmatch.fnmatch(file, suffix): + continue + file_path = os.path.join(cur_dir, file) + with open(file_path, errors="replace") as f: + for line in f: + count_line(line) + + +if __name__ == '__main__': + scan_dir(r"../..") + print("Total lines:%d" % total_lines) + print("Code lines:%d" % code_lines) + print("Empty lines:%d" % empty_lines) + print("Comment lines:%d" % comment_lines) diff --git a/PyBeaner/0008/text_in_html.py b/PyBeaner/0008/text_in_html.py new file mode 100644 index 00000000..a184018d --- /dev/null +++ b/PyBeaner/0008/text_in_html.py @@ -0,0 +1,21 @@ +# coding=utf-8 +__author__ = 'PyBeaner' +from bs4 import BeautifulSoup + + +def get_text(html): + soup = BeautifulSoup(html) + return soup.text + + +if __name__ == '__main__': + import requests + + r = requests.get("https://github.com/") + html = r.text + text = get_text(html) + with open("html.txt", "w+", errors="replace") as f: + print(text, file=f) + f.seek(0) + for line in f: + print(line) diff --git a/PyBeaner/0009/link_in_html.py b/PyBeaner/0009/link_in_html.py new file mode 100644 index 00000000..f78f8d07 --- /dev/null +++ b/PyBeaner/0009/link_in_html.py @@ -0,0 +1,22 @@ +# coding=utf-8 +__author__ = 'PyBeaner' +from bs4 import BeautifulSoup + + +def get_links(html): + soup = BeautifulSoup(html) + links = [] + for link in soup.find_all("a"): + href = link["href"] + if href.startswith("http"): + links.append(href) + return links + + +if __name__ == '__main__': + import requests + + r = requests.get("https://github.com/") + html = r.text + links = get_links(html) + print(links) diff --git a/PyBeaner/0011/filter.py b/PyBeaner/0011/filter.py new file mode 100644 index 00000000..03633390 --- /dev/null +++ b/PyBeaner/0011/filter.py @@ -0,0 +1,9 @@ +__author__ = 'PyBeaner' + +words = open("filtered_words.txt").read().split() + +word = input("Please Input an word:") +if word in words: + print("Freedom") +else: + print("Human Rights") diff --git a/PyBeaner/0011/filtered_words.txt b/PyBeaner/0011/filtered_words.txt new file mode 100644 index 00000000..444eb7c6 --- /dev/null +++ b/PyBeaner/0011/filtered_words.txt @@ -0,0 +1,11 @@ + +Ա +Ա +쵼 +ţ +ţ + + +love +sex +jiangge \ No newline at end of file diff --git a/PyBeaner/0012/filter.py b/PyBeaner/0012/filter.py new file mode 100644 index 00000000..4e272ce6 --- /dev/null +++ b/PyBeaner/0012/filter.py @@ -0,0 +1,9 @@ +__author__ = 'PyBeaner' +words = open("filtered_words.txt").read().split() + +user_input = input("Please Input an word:") + +for word in words: + user_input = user_input.replace(word, "*" * len(word)) + +print(user_input) diff --git a/PyBeaner/0012/filtered_words.txt b/PyBeaner/0012/filtered_words.txt new file mode 100644 index 00000000..444eb7c6 --- /dev/null +++ b/PyBeaner/0012/filtered_words.txt @@ -0,0 +1,11 @@ + +Ա +Ա +쵼 +ţ +ţ + + +love +sex +jiangge \ No newline at end of file diff --git a/PyBeaner/__init__.py b/PyBeaner/__init__.py new file mode 100644 index 00000000..88c7a442 --- /dev/null +++ b/PyBeaner/__init__.py @@ -0,0 +1 @@ +__author__ = 'PyBeaner' diff --git a/README.md b/README.md index 35ee7952..7b884541 100644 --- a/README.md +++ b/README.md @@ -3,6 +3,8 @@ python Show Me the Code Python version. +2015年8月10日更新: +【注】Pull Request 请提交你个人的仓库 URL 链接地址。 ### How to Add your solutions: diff --git a/Raynxxx/0000/ex00.py b/Raynxxx/0000/ex00.py new file mode 100644 index 00000000..e67b0805 --- /dev/null +++ b/Raynxxx/0000/ex00.py @@ -0,0 +1,38 @@ +__author__ = 'rayn' + +#problem 0000 +#Add a unread number on the face icon + +from PIL import Image +from PIL import ImageFont +from PIL import ImageDraw + +class UnreadTagFace: + def __init__(self): + self.img = None + self.num = None + def open(self, image_path): + self.img = Image.open(image_path) + return True + def draw(self, tag_num = 1): + tag_size = max(self.img.size[0], self.img.size[1]) / 5 + tag_str = str(tag_num) if tag_num < 100 else '99+' + font = ImageFont.truetype("Arial.ttf", tag_size) + px = self.img.size[0] - font.getsize(tag_str)[0] + draw_pen = ImageDraw.Draw(self.img) + draw_pen.text((px, 0), tag_str, (255, 0, 0), font) + self.img.save('face' + tag_str + '.jpg') + return True + + +solver = UnreadTagFace() +solver.open('face.jpg') +solver.draw(4) + + + + + + + + diff --git a/ShaoyuanLi/0000/a.png b/ShaoyuanLi/0000/a.png new file mode 100644 index 00000000..5f6b0113 Binary files /dev/null and b/ShaoyuanLi/0000/a.png differ diff --git a/ShaoyuanLi/0000/example.py b/ShaoyuanLi/0000/example.py new file mode 100644 index 00000000..c04af4d6 --- /dev/null +++ b/ShaoyuanLi/0000/example.py @@ -0,0 +1,9 @@ +import Image,ImageDraw,ImageFont + +myfont=ImageFont.truetype("arial.ttf", 35) +im=Image.open("touxiang.png") +draw=ImageDraw.Draw(im) +x,y=im.size +draw.text((x-x/5,y/8),"8",fill=(255,0,0),font=myfont) +im.save("result.png", "PNG") + diff --git a/ShaoyuanLi/0000/exmaple.py b/ShaoyuanLi/0000/exmaple.py new file mode 100644 index 00000000..c04af4d6 --- /dev/null +++ b/ShaoyuanLi/0000/exmaple.py @@ -0,0 +1,9 @@ +import Image,ImageDraw,ImageFont + +myfont=ImageFont.truetype("arial.ttf", 35) +im=Image.open("touxiang.png") +draw=ImageDraw.Draw(im) +x,y=im.size +draw.text((x-x/5,y/8),"8",fill=(255,0,0),font=myfont) +im.save("result.png", "PNG") + diff --git a/ShaoyuanLi/0000/touxiang.png b/ShaoyuanLi/0000/touxiang.png new file mode 100644 index 00000000..c3222d12 Binary files /dev/null and b/ShaoyuanLi/0000/touxiang.png differ diff --git a/ShaoyuanLi/0001/0001.py b/ShaoyuanLi/0001/0001.py new file mode 100644 index 00000000..278979a6 --- /dev/null +++ b/ShaoyuanLi/0001/0001.py @@ -0,0 +1,24 @@ +# -*- coding: cp936 -*- +import random +#200鳤Ϊ8Ż룬ֵ伯ּĸ +def generate_key(number=200,length=8): + char_set="abcdefghijklmnopqrstuvwxyz0123456789" + result="" + for i in range(0, number): + temp="" + while(temp==""): + for j in range(0,length): + temp=temp+char_set[random.randint(0,35)] +#жɵŻǷ֮ǰظ + if(result.find(temp)==-1): + result=result+"%d "%(i+1)+temp + else: + temp="" + result=result+'\n' + return result +def file_write(): + fp=open("result.txt",'w') + fp.writelines(generate_key()) + fp.close() +if __name__ == '__main__': + file_write() diff --git a/ShaoyuanLi/0001/result.txt b/ShaoyuanLi/0001/result.txt new file mode 100644 index 00000000..8b16cadb --- /dev/null +++ b/ShaoyuanLi/0001/result.txt @@ -0,0 +1,200 @@ +1 nxmmjq5u +2 5hoe20v9 +3 elb1hrv0 +4 ls6htkmx +5 qwzg0o39 +6 97reovrl +7 zcwu57gj +8 gk8cgovi +9 prciw3q0 +10 vnf9n6b8 +11 fps1hiqw +12 j33wf93a +13 zwue5e71 +14 0nissnay +15 feghkqmx +16 io4kuhcq +17 x6u8t76p +18 1h61e4ng +19 qbl5ebk8 +20 6jual6xm +21 vjocsl6m +22 n61d32ud +23 p4m2iphq +24 pyacaotz +25 04qoagrf +26 6crk5pqt +27 s3ahsg3m +28 mqzy3c6s +29 sn7zd09i +30 cf8zzveh +31 xsudv4pb +32 trnqj7fp +33 wcm0p84l +34 4ipcf95a +35 s9xq6xcy +36 phpz7h8l +37 o91mes3g +38 t6uknpae +39 z6c5xi23 +40 yye3x973 +41 er1yto5z +42 sfap7fsl +43 bziiqf36 +44 ybg4dhmk +45 y1mmf067 +46 33118f0r +47 z5qmqqq7 +48 ryb0k7zw +49 tedbcsxp +50 yeq6xacz +51 sgxvn5ji +52 klymd488 +53 xfmwvjq2 +54 auy0dic5 +55 gis55ucl +56 mcq6cr17 +57 o96zscnz +58 hk2rlohj +59 0ntnb0q4 +60 xw1v4xel +61 nha9skdv +62 k1kv2y97 +63 gbfz5l0v +64 an80u8wr +65 4pc3njpa +66 6it3rlw7 +67 6mj7rtab +68 9uahvgry +69 680wn4my +70 251guth4 +71 zjd0za7k +72 n0z7wbeh +73 j0h3jjvz +74 f9oux370 +75 8sky09ux +76 eax249ug +77 477aqrpo +78 vucjphwm +79 ud32a2e4 +80 nhquv87l +81 f4um10au +82 m5jkru0w +83 rpvzm6tm +84 dykl1h4p +85 zmuwu3o0 +86 j7giqlex +87 vwa69otf +88 6sha6mfq +89 fpdf4wm1 +90 c04s7ymz +91 ks87sv0b +92 jhshq4xo +93 96zplwyn +94 muahr9je +95 t218gs1g +96 xcs602r5 +97 2d44deyq +98 pdh1yvgf +99 tejxc3xc +100 ci2bx2y0 +101 ei2ic9q3 +102 1txrhspe +103 0ut7su6t +104 nc90orev +105 67dn6ccd +106 6eopvnqi +107 a8klb1uz +108 nwrqv1q4 +109 hz8r2ylb +110 dnklsvf8 +111 t300hvo2 +112 lx35alfv +113 42061qcj +114 na4roat2 +115 3cpr59zl +116 cwtfdnw1 +117 ig13dgp8 +118 1l00kvoe +119 pzeijnui +120 cquvplvg +121 46os5qq4 +122 0gnccy9u +123 utcbxjxy +124 tfy5z7oj +125 9c90fgqa +126 z8c4glb3 +127 vhvx6jsw +128 at0dknzh +129 3t4n1zmw +130 ohzbmj4m +131 8yw8thmv +132 eafvf0u2 +133 9k74zdd9 +134 s5wnndk8 +135 pzn80syp +136 pwwrz5y3 +137 x4j7ea5q +138 tyd2pf35 +139 lxz2tyso +140 4sjkim2k +141 hkgxx7zo +142 xfci5bvl +143 6m9ejxq6 +144 wfw60y3x +145 yqvlczdy +146 1xddbfio +147 6emvqho0 +148 l4x17hf6 +149 fm5eibvy +150 l8vvvosj +151 wbhffvzm +152 zwzcsx91 +153 q7xxd9fw +154 x0xxczvo +155 avp7wbsd +156 2pqfl04c +157 ropj6jx6 +158 andgzoxe +159 xn11gqgu +160 cc31xxhx +161 22cuf67k +162 ikuypkzs +163 k2hawt99 +164 kb2f3z36 +165 wwdpa84t +166 qcmqffx9 +167 1ia6qv0s +168 5s2flplu +169 bk1vseyl +170 h1eq9td4 +171 b18q9a62 +172 daryg2hx +173 2poyp7tt +174 9xhoyk5q +175 xcav6ut9 +176 j0wuv9hk +177 cfyradja +178 79kb1jmr +179 jdo0ydys +180 zyfy4yly +181 dsr2j44o +182 xfh51sce +183 44gzcgpf +184 x6kh99np +185 asr1r9vu +186 27hiy93f +187 ggl2442w +188 jmkf60w7 +189 qrhax89p +190 whuhnbtc +191 74hvzjlh +192 05xfn6y8 +193 7gp768d5 +194 cu3o1xm1 +195 6hchvuy6 +196 ki975jre +197 9q296wk4 +198 48l0a9nv +199 ssx4zopx +200 yscuw50k diff --git a/ShaoyuanLi/0004/0004.py b/ShaoyuanLi/0004/0004.py new file mode 100644 index 00000000..c80d04e8 --- /dev/null +++ b/ShaoyuanLi/0004/0004.py @@ -0,0 +1,19 @@ +# -*- coding: cp936 -*- +import re +fin=open("example.txt","r") +fout=open("result.txt","w") +str=fin.read() +#ƥʽ +reObj=re.compile("\b?([a-zA-Z]+)\b?") +words=reObj.findall(str) +#ֵ +word_dict={} +#ԵʵСдΪֵͳƣͬʱҪ +for word in words: + if(word_dict.has_key(word)): + word_dict[word.lower()]=max(word_dict[word.lower()],words.count(word.lower())+words.count(word.upper())+words.count(word)) + else: + word_dict[word.lower()]=max(0,words.count(word.lower())+words.count(word.upper())+words.count(word)) +for(word,number) in word_dict.items(): + fout.write(word+":%d\n"%number) + diff --git a/ShaoyuanLi/0004/example.txt b/ShaoyuanLi/0004/example.txt new file mode 100644 index 00000000..fd6c17d4 --- /dev/null +++ b/ShaoyuanLi/0004/example.txt @@ -0,0 +1 @@ +In the latest move to support the economy, Shanghai, Beijing, Chongqing and six other provinces and municipalities will allow banks to refinance high-quality credit assets rated by the People's Bank of China, said the central bank, as the program was first introduced in Guangdong and Shandong provinces last year. \ No newline at end of file diff --git a/ShaoyuanLi/0004/result.txt b/ShaoyuanLi/0004/result.txt new file mode 100644 index 00000000..aa415b37 --- /dev/null +++ b/ShaoyuanLi/0004/result.txt @@ -0,0 +1,41 @@ +and:6 +beijing:1 +shandong:1 +six:2 +people:1 +move:2 +year:2 +high:2 +as:2 +program:2 +in:2 +guangdong:1 +quality:2 +provinces:4 +rated:2 +support:2 +shanghai:1 +to:4 +other:2 +was:2 +economy:2 +municipalities:2 +refinance:2 +said:2 +china:1 +last:2 +by:2 +bank:2 +chongqing:1 +introduced:2 +central:2 +assets:2 +of:2 +will:2 +credit:2 +s:2 +allow:2 +banks:2 +the:10 +first:2 +latest:2 diff --git a/Silocean/0000/DejaVuSansMono.ttf b/Silocean/0000/DejaVuSansMono.ttf new file mode 100644 index 00000000..9bebb47e Binary files /dev/null and b/Silocean/0000/DejaVuSansMono.ttf differ diff --git a/Silocean/0000/Test.py b/Silocean/0000/Test.py new file mode 100644 index 00000000..d1b6c689 --- /dev/null +++ b/Silocean/0000/Test.py @@ -0,0 +1,18 @@ +# -*- coding: utf-8 -*- +""" +Created on Fri Jun 5 13:40:53 2015 + +@author: Tracy +""" + +from PIL import Image +from PIL import ImageDraw +from PIL import ImageFont + +img = Image.open('icon.jpg') +draw = ImageDraw.Draw(img) +font = ImageFont.truetype('DejaVuSansMono.ttf',100) + +draw.text((img.size[0]-100,30),"3",(255,0,0), font) + +img.save('result.jpg') diff --git a/Silocean/0001/Test.py b/Silocean/0001/Test.py new file mode 100644 index 00000000..6c2d780c --- /dev/null +++ b/Silocean/0001/Test.py @@ -0,0 +1,12 @@ +# -*-coding:utf-8-*- +__author__ = 'Tracy' + +import uuid + +f = open('keys.txt', 'w') + +for i in range(200): + f.write(str(uuid.uuid1())+"\n") + +f.close() + diff --git a/Silocean/0001/keys.txt b/Silocean/0001/keys.txt new file mode 100644 index 00000000..bc2a4a6c --- /dev/null +++ b/Silocean/0001/keys.txt @@ -0,0 +1,200 @@ +2d41c530-0f55-11e5-8f5c-005056c00008 +2d42af8f-0f55-11e5-b4d8-005056c00008 +2d42af90-0f55-11e5-b7bb-005056c00008 +2d42af91-0f55-11e5-b9a1-005056c00008 +2d42af92-0f55-11e5-bf53-005056c00008 +2d42af93-0f55-11e5-bc30-005056c00008 +2d42af94-0f55-11e5-9f13-005056c00008 +2d42d69e-0f55-11e5-97ef-005056c00008 +2d42d69f-0f55-11e5-b24e-005056c00008 +2d42d6a0-0f55-11e5-9a7d-005056c00008 +2d42d6a1-0f55-11e5-8a21-005056c00008 +2d42d6a2-0f55-11e5-aa17-005056c00008 +2d42d6a3-0f55-11e5-8808-005056c00008 +2d42d6a4-0f55-11e5-b193-005056c00008 +2d42d6a5-0f55-11e5-b34f-005056c00008 +2d42d6a6-0f55-11e5-ae3a-005056c00008 +2d42d6a7-0f55-11e5-867a-005056c00008 +2d42d6a8-0f55-11e5-94f6-005056c00008 +2d42d6a9-0f55-11e5-8ccf-005056c00008 +2d42d6aa-0f55-11e5-9956-005056c00008 +2d42d6ab-0f55-11e5-b154-005056c00008 +2d42d6ac-0f55-11e5-be92-005056c00008 +2d42d6ad-0f55-11e5-ac5c-005056c00008 +2d42d6ae-0f55-11e5-a12a-005056c00008 +2d42d6af-0f55-11e5-88f8-005056c00008 +2d42d6b0-0f55-11e5-9a80-005056c00008 +2d42d6b1-0f55-11e5-ab69-005056c00008 +2d42d6b2-0f55-11e5-aa4e-005056c00008 +2d42d6b3-0f55-11e5-b419-005056c00008 +2d42d6b4-0f55-11e5-be0e-005056c00008 +2d42d6b5-0f55-11e5-8e0a-005056c00008 +2d42d6b6-0f55-11e5-8e7e-005056c00008 +2d42d6b7-0f55-11e5-9193-005056c00008 +2d42d6b8-0f55-11e5-a974-005056c00008 +2d42d6b9-0f55-11e5-84bb-005056c00008 +2d42d6ba-0f55-11e5-b16a-005056c00008 +2d42d6bb-0f55-11e5-a432-005056c00008 +2d42d6bc-0f55-11e5-b2cb-005056c00008 +2d42d6bd-0f55-11e5-b6a8-005056c00008 +2d42d6be-0f55-11e5-806a-005056c00008 +2d42d6bf-0f55-11e5-9979-005056c00008 +2d42d6c0-0f55-11e5-8f31-005056c00008 +2d42d6c1-0f55-11e5-9f4b-005056c00008 +2d42d6c2-0f55-11e5-afa9-005056c00008 +2d42d6c3-0f55-11e5-9718-005056c00008 +2d42d6c4-0f55-11e5-b206-005056c00008 +2d42d6c5-0f55-11e5-857c-005056c00008 +2d42d6c6-0f55-11e5-b451-005056c00008 +2d42d6c7-0f55-11e5-ae68-005056c00008 +2d42d6c8-0f55-11e5-8b37-005056c00008 +2d42d6c9-0f55-11e5-944b-005056c00008 +2d42d6ca-0f55-11e5-9348-005056c00008 +2d42d6cb-0f55-11e5-b068-005056c00008 +2d42d6cc-0f55-11e5-9457-005056c00008 +2d42d6cd-0f55-11e5-8d79-005056c00008 +2d42d6ce-0f55-11e5-9e25-005056c00008 +2d42d6cf-0f55-11e5-b0b3-005056c00008 +2d42d6d0-0f55-11e5-a097-005056c00008 +2d42d6d1-0f55-11e5-85d4-005056c00008 +2d42fdae-0f55-11e5-976f-005056c00008 +2d42fdaf-0f55-11e5-a37b-005056c00008 +2d42fdb0-0f55-11e5-905e-005056c00008 +2d42fdb1-0f55-11e5-83af-005056c00008 +2d42fdb2-0f55-11e5-b541-005056c00008 +2d42fdb3-0f55-11e5-b6e0-005056c00008 +2d42fdb4-0f55-11e5-b07b-005056c00008 +2d42fdb5-0f55-11e5-b458-005056c00008 +2d42fdb6-0f55-11e5-927d-005056c00008 +2d42fdb7-0f55-11e5-9bb9-005056c00008 +2d42fdb8-0f55-11e5-a37e-005056c00008 +2d42fdb9-0f55-11e5-9b60-005056c00008 +2d42fdba-0f55-11e5-8b8b-005056c00008 +2d42fdbb-0f55-11e5-bc71-005056c00008 +2d42fdbc-0f55-11e5-a6a3-005056c00008 +2d42fdbd-0f55-11e5-95eb-005056c00008 +2d42fdbe-0f55-11e5-b6c7-005056c00008 +2d42fdbf-0f55-11e5-8022-005056c00008 +2d42fdc0-0f55-11e5-91e1-005056c00008 +2d42fdc1-0f55-11e5-881e-005056c00008 +2d42fdc2-0f55-11e5-bbf8-005056c00008 +2d42fdc3-0f55-11e5-82cc-005056c00008 +2d42fdc4-0f55-11e5-b432-005056c00008 +2d42fdc5-0f55-11e5-9b5e-005056c00008 +2d42fdc6-0f55-11e5-9569-005056c00008 +2d42fdc7-0f55-11e5-93cb-005056c00008 +2d42fdc8-0f55-11e5-ac62-005056c00008 +2d42fdc9-0f55-11e5-8546-005056c00008 +2d42fdca-0f55-11e5-94a2-005056c00008 +2d42fdcb-0f55-11e5-aaa3-005056c00008 +2d42fdcc-0f55-11e5-8662-005056c00008 +2d42fdcd-0f55-11e5-8754-005056c00008 +2d42fdce-0f55-11e5-921d-005056c00008 +2d42fdcf-0f55-11e5-87f1-005056c00008 +2d42fdd0-0f55-11e5-8f64-005056c00008 +2d42fdd1-0f55-11e5-865c-005056c00008 +2d42fdd2-0f55-11e5-82fe-005056c00008 +2d42fdd3-0f55-11e5-a5c7-005056c00008 +2d42fdd4-0f55-11e5-8040-005056c00008 +2d42fdd5-0f55-11e5-b875-005056c00008 +2d42fdd6-0f55-11e5-9c3e-005056c00008 +2d42fdd7-0f55-11e5-8f2d-005056c00008 +2d42fdd8-0f55-11e5-8a4a-005056c00008 +2d42fdd9-0f55-11e5-b183-005056c00008 +2d42fdda-0f55-11e5-b57f-005056c00008 +2d42fddb-0f55-11e5-8df2-005056c00008 +2d42fddc-0f55-11e5-b25f-005056c00008 +2d42fddd-0f55-11e5-b1a7-005056c00008 +2d42fdde-0f55-11e5-8a7e-005056c00008 +2d42fddf-0f55-11e5-8e69-005056c00008 +2d42fde0-0f55-11e5-b08c-005056c00008 +2d42fde1-0f55-11e5-8b4d-005056c00008 +2d4324c0-0f55-11e5-8a3d-005056c00008 +2d4324c1-0f55-11e5-8e21-005056c00008 +2d4324c2-0f55-11e5-a739-005056c00008 +2d4324c3-0f55-11e5-be1c-005056c00008 +2d4324c4-0f55-11e5-b3cb-005056c00008 +2d4324c5-0f55-11e5-8f7f-005056c00008 +2d4324c6-0f55-11e5-8e36-005056c00008 +2d4324c7-0f55-11e5-b89a-005056c00008 +2d4324c8-0f55-11e5-ba2f-005056c00008 +2d4324c9-0f55-11e5-bde1-005056c00008 +2d4324ca-0f55-11e5-b995-005056c00008 +2d4324cb-0f55-11e5-9dff-005056c00008 +2d4324cc-0f55-11e5-ae22-005056c00008 +2d4324cd-0f55-11e5-b3a8-005056c00008 +2d4324ce-0f55-11e5-9d75-005056c00008 +2d4324cf-0f55-11e5-a491-005056c00008 +2d4324d0-0f55-11e5-a95b-005056c00008 +2d4324d1-0f55-11e5-87cc-005056c00008 +2d4324d2-0f55-11e5-9002-005056c00008 +2d4324d3-0f55-11e5-a70a-005056c00008 +2d4324d4-0f55-11e5-82d0-005056c00008 +2d4324d5-0f55-11e5-99f9-005056c00008 +2d4324d6-0f55-11e5-bb48-005056c00008 +2d4324d7-0f55-11e5-86bf-005056c00008 +2d4324d8-0f55-11e5-abe3-005056c00008 +2d4324d9-0f55-11e5-8ca4-005056c00008 +2d4324da-0f55-11e5-9ab8-005056c00008 +2d4324db-0f55-11e5-bbc0-005056c00008 +2d4324dc-0f55-11e5-829f-005056c00008 +2d4324dd-0f55-11e5-b85f-005056c00008 +2d4324de-0f55-11e5-9924-005056c00008 +2d4324df-0f55-11e5-be66-005056c00008 +2d4324e0-0f55-11e5-a782-005056c00008 +2d4324e1-0f55-11e5-a1bb-005056c00008 +2d4324e2-0f55-11e5-9a39-005056c00008 +2d4324e3-0f55-11e5-afa4-005056c00008 +2d4324e4-0f55-11e5-b056-005056c00008 +2d4324e5-0f55-11e5-b9aa-005056c00008 +2d4324e6-0f55-11e5-be9f-005056c00008 +2d4324e7-0f55-11e5-bb63-005056c00008 +2d4324e8-0f55-11e5-9953-005056c00008 +2d4324e9-0f55-11e5-b38a-005056c00008 +2d4324ea-0f55-11e5-b6c3-005056c00008 +2d4324eb-0f55-11e5-8263-005056c00008 +2d4324ec-0f55-11e5-9614-005056c00008 +2d4324ed-0f55-11e5-adac-005056c00008 +2d4324ee-0f55-11e5-b14c-005056c00008 +2d4324ef-0f55-11e5-9b03-005056c00008 +2d4324f0-0f55-11e5-b170-005056c00008 +2d4324f1-0f55-11e5-a4c5-005056c00008 +2d4324f2-0f55-11e5-8339-005056c00008 +2d4324f3-0f55-11e5-9e09-005056c00008 +2d4324f4-0f55-11e5-9f87-005056c00008 +2d4324f5-0f55-11e5-b5d5-005056c00008 +2d4324f6-0f55-11e5-bdda-005056c00008 +2d4324f7-0f55-11e5-a302-005056c00008 +2d4324f8-0f55-11e5-9cfc-005056c00008 +2d4324f9-0f55-11e5-bf30-005056c00008 +2d434bcf-0f55-11e5-b117-005056c00008 +2d434bd0-0f55-11e5-9677-005056c00008 +2d434bd1-0f55-11e5-9433-005056c00008 +2d434bd2-0f55-11e5-a0a9-005056c00008 +2d434bd3-0f55-11e5-80e1-005056c00008 +2d434bd4-0f55-11e5-a504-005056c00008 +2d434bd5-0f55-11e5-9d0e-005056c00008 +2d434bd6-0f55-11e5-afd2-005056c00008 +2d434bd7-0f55-11e5-a37b-005056c00008 +2d434bd8-0f55-11e5-8ac6-005056c00008 +2d434bd9-0f55-11e5-b15d-005056c00008 +2d434bda-0f55-11e5-9adf-005056c00008 +2d434bdb-0f55-11e5-a36b-005056c00008 +2d434bdc-0f55-11e5-adaa-005056c00008 +2d434bdd-0f55-11e5-b1f0-005056c00008 +2d434bde-0f55-11e5-b3e3-005056c00008 +2d434bdf-0f55-11e5-a63c-005056c00008 +2d434be0-0f55-11e5-a2bc-005056c00008 +2d434be1-0f55-11e5-9879-005056c00008 +2d434be2-0f55-11e5-a762-005056c00008 +2d434be3-0f55-11e5-960f-005056c00008 +2d434be4-0f55-11e5-a09d-005056c00008 +2d434be5-0f55-11e5-9ac9-005056c00008 +2d434be6-0f55-11e5-a32e-005056c00008 +2d434be7-0f55-11e5-be33-005056c00008 +2d434be8-0f55-11e5-9ce6-005056c00008 +2d434be9-0f55-11e5-89cc-005056c00008 +2d434bea-0f55-11e5-bfaf-005056c00008 +2d434beb-0f55-11e5-ba34-005056c00008 +2d434bec-0f55-11e5-9d7f-005056c00008 +2d434bed-0f55-11e5-ad4a-005056c00008 diff --git a/Silocean/0002/Test.py b/Silocean/0002/Test.py new file mode 100644 index 00000000..d2ecb32d --- /dev/null +++ b/Silocean/0002/Test.py @@ -0,0 +1,19 @@ +# -*-coding:utf-8-*- +__author__ = 'Tracy' + +import MySQLdb + +conn = MySQLdb.connect('localhost', 'root', '123456', 'test', charset='utf8') +cursor = conn.cursor() + +sql = 'create table if not exists mykeys (key_id char(36) not null)' +cursor.execute(sql) + +with open('keys.txt', 'r') as f: + keys = f.readlines() + for key in keys: + cursor.execute("insert into mykeys values ('%s')" % str(key)) + +cursor.close() +conn.commit() +conn.close() \ No newline at end of file diff --git a/Silocean/0002/keys.txt b/Silocean/0002/keys.txt new file mode 100644 index 00000000..bc2a4a6c --- /dev/null +++ b/Silocean/0002/keys.txt @@ -0,0 +1,200 @@ +2d41c530-0f55-11e5-8f5c-005056c00008 +2d42af8f-0f55-11e5-b4d8-005056c00008 +2d42af90-0f55-11e5-b7bb-005056c00008 +2d42af91-0f55-11e5-b9a1-005056c00008 +2d42af92-0f55-11e5-bf53-005056c00008 +2d42af93-0f55-11e5-bc30-005056c00008 +2d42af94-0f55-11e5-9f13-005056c00008 +2d42d69e-0f55-11e5-97ef-005056c00008 +2d42d69f-0f55-11e5-b24e-005056c00008 +2d42d6a0-0f55-11e5-9a7d-005056c00008 +2d42d6a1-0f55-11e5-8a21-005056c00008 +2d42d6a2-0f55-11e5-aa17-005056c00008 +2d42d6a3-0f55-11e5-8808-005056c00008 +2d42d6a4-0f55-11e5-b193-005056c00008 +2d42d6a5-0f55-11e5-b34f-005056c00008 +2d42d6a6-0f55-11e5-ae3a-005056c00008 +2d42d6a7-0f55-11e5-867a-005056c00008 +2d42d6a8-0f55-11e5-94f6-005056c00008 +2d42d6a9-0f55-11e5-8ccf-005056c00008 +2d42d6aa-0f55-11e5-9956-005056c00008 +2d42d6ab-0f55-11e5-b154-005056c00008 +2d42d6ac-0f55-11e5-be92-005056c00008 +2d42d6ad-0f55-11e5-ac5c-005056c00008 +2d42d6ae-0f55-11e5-a12a-005056c00008 +2d42d6af-0f55-11e5-88f8-005056c00008 +2d42d6b0-0f55-11e5-9a80-005056c00008 +2d42d6b1-0f55-11e5-ab69-005056c00008 +2d42d6b2-0f55-11e5-aa4e-005056c00008 +2d42d6b3-0f55-11e5-b419-005056c00008 +2d42d6b4-0f55-11e5-be0e-005056c00008 +2d42d6b5-0f55-11e5-8e0a-005056c00008 +2d42d6b6-0f55-11e5-8e7e-005056c00008 +2d42d6b7-0f55-11e5-9193-005056c00008 +2d42d6b8-0f55-11e5-a974-005056c00008 +2d42d6b9-0f55-11e5-84bb-005056c00008 +2d42d6ba-0f55-11e5-b16a-005056c00008 +2d42d6bb-0f55-11e5-a432-005056c00008 +2d42d6bc-0f55-11e5-b2cb-005056c00008 +2d42d6bd-0f55-11e5-b6a8-005056c00008 +2d42d6be-0f55-11e5-806a-005056c00008 +2d42d6bf-0f55-11e5-9979-005056c00008 +2d42d6c0-0f55-11e5-8f31-005056c00008 +2d42d6c1-0f55-11e5-9f4b-005056c00008 +2d42d6c2-0f55-11e5-afa9-005056c00008 +2d42d6c3-0f55-11e5-9718-005056c00008 +2d42d6c4-0f55-11e5-b206-005056c00008 +2d42d6c5-0f55-11e5-857c-005056c00008 +2d42d6c6-0f55-11e5-b451-005056c00008 +2d42d6c7-0f55-11e5-ae68-005056c00008 +2d42d6c8-0f55-11e5-8b37-005056c00008 +2d42d6c9-0f55-11e5-944b-005056c00008 +2d42d6ca-0f55-11e5-9348-005056c00008 +2d42d6cb-0f55-11e5-b068-005056c00008 +2d42d6cc-0f55-11e5-9457-005056c00008 +2d42d6cd-0f55-11e5-8d79-005056c00008 +2d42d6ce-0f55-11e5-9e25-005056c00008 +2d42d6cf-0f55-11e5-b0b3-005056c00008 +2d42d6d0-0f55-11e5-a097-005056c00008 +2d42d6d1-0f55-11e5-85d4-005056c00008 +2d42fdae-0f55-11e5-976f-005056c00008 +2d42fdaf-0f55-11e5-a37b-005056c00008 +2d42fdb0-0f55-11e5-905e-005056c00008 +2d42fdb1-0f55-11e5-83af-005056c00008 +2d42fdb2-0f55-11e5-b541-005056c00008 +2d42fdb3-0f55-11e5-b6e0-005056c00008 +2d42fdb4-0f55-11e5-b07b-005056c00008 +2d42fdb5-0f55-11e5-b458-005056c00008 +2d42fdb6-0f55-11e5-927d-005056c00008 +2d42fdb7-0f55-11e5-9bb9-005056c00008 +2d42fdb8-0f55-11e5-a37e-005056c00008 +2d42fdb9-0f55-11e5-9b60-005056c00008 +2d42fdba-0f55-11e5-8b8b-005056c00008 +2d42fdbb-0f55-11e5-bc71-005056c00008 +2d42fdbc-0f55-11e5-a6a3-005056c00008 +2d42fdbd-0f55-11e5-95eb-005056c00008 +2d42fdbe-0f55-11e5-b6c7-005056c00008 +2d42fdbf-0f55-11e5-8022-005056c00008 +2d42fdc0-0f55-11e5-91e1-005056c00008 +2d42fdc1-0f55-11e5-881e-005056c00008 +2d42fdc2-0f55-11e5-bbf8-005056c00008 +2d42fdc3-0f55-11e5-82cc-005056c00008 +2d42fdc4-0f55-11e5-b432-005056c00008 +2d42fdc5-0f55-11e5-9b5e-005056c00008 +2d42fdc6-0f55-11e5-9569-005056c00008 +2d42fdc7-0f55-11e5-93cb-005056c00008 +2d42fdc8-0f55-11e5-ac62-005056c00008 +2d42fdc9-0f55-11e5-8546-005056c00008 +2d42fdca-0f55-11e5-94a2-005056c00008 +2d42fdcb-0f55-11e5-aaa3-005056c00008 +2d42fdcc-0f55-11e5-8662-005056c00008 +2d42fdcd-0f55-11e5-8754-005056c00008 +2d42fdce-0f55-11e5-921d-005056c00008 +2d42fdcf-0f55-11e5-87f1-005056c00008 +2d42fdd0-0f55-11e5-8f64-005056c00008 +2d42fdd1-0f55-11e5-865c-005056c00008 +2d42fdd2-0f55-11e5-82fe-005056c00008 +2d42fdd3-0f55-11e5-a5c7-005056c00008 +2d42fdd4-0f55-11e5-8040-005056c00008 +2d42fdd5-0f55-11e5-b875-005056c00008 +2d42fdd6-0f55-11e5-9c3e-005056c00008 +2d42fdd7-0f55-11e5-8f2d-005056c00008 +2d42fdd8-0f55-11e5-8a4a-005056c00008 +2d42fdd9-0f55-11e5-b183-005056c00008 +2d42fdda-0f55-11e5-b57f-005056c00008 +2d42fddb-0f55-11e5-8df2-005056c00008 +2d42fddc-0f55-11e5-b25f-005056c00008 +2d42fddd-0f55-11e5-b1a7-005056c00008 +2d42fdde-0f55-11e5-8a7e-005056c00008 +2d42fddf-0f55-11e5-8e69-005056c00008 +2d42fde0-0f55-11e5-b08c-005056c00008 +2d42fde1-0f55-11e5-8b4d-005056c00008 +2d4324c0-0f55-11e5-8a3d-005056c00008 +2d4324c1-0f55-11e5-8e21-005056c00008 +2d4324c2-0f55-11e5-a739-005056c00008 +2d4324c3-0f55-11e5-be1c-005056c00008 +2d4324c4-0f55-11e5-b3cb-005056c00008 +2d4324c5-0f55-11e5-8f7f-005056c00008 +2d4324c6-0f55-11e5-8e36-005056c00008 +2d4324c7-0f55-11e5-b89a-005056c00008 +2d4324c8-0f55-11e5-ba2f-005056c00008 +2d4324c9-0f55-11e5-bde1-005056c00008 +2d4324ca-0f55-11e5-b995-005056c00008 +2d4324cb-0f55-11e5-9dff-005056c00008 +2d4324cc-0f55-11e5-ae22-005056c00008 +2d4324cd-0f55-11e5-b3a8-005056c00008 +2d4324ce-0f55-11e5-9d75-005056c00008 +2d4324cf-0f55-11e5-a491-005056c00008 +2d4324d0-0f55-11e5-a95b-005056c00008 +2d4324d1-0f55-11e5-87cc-005056c00008 +2d4324d2-0f55-11e5-9002-005056c00008 +2d4324d3-0f55-11e5-a70a-005056c00008 +2d4324d4-0f55-11e5-82d0-005056c00008 +2d4324d5-0f55-11e5-99f9-005056c00008 +2d4324d6-0f55-11e5-bb48-005056c00008 +2d4324d7-0f55-11e5-86bf-005056c00008 +2d4324d8-0f55-11e5-abe3-005056c00008 +2d4324d9-0f55-11e5-8ca4-005056c00008 +2d4324da-0f55-11e5-9ab8-005056c00008 +2d4324db-0f55-11e5-bbc0-005056c00008 +2d4324dc-0f55-11e5-829f-005056c00008 +2d4324dd-0f55-11e5-b85f-005056c00008 +2d4324de-0f55-11e5-9924-005056c00008 +2d4324df-0f55-11e5-be66-005056c00008 +2d4324e0-0f55-11e5-a782-005056c00008 +2d4324e1-0f55-11e5-a1bb-005056c00008 +2d4324e2-0f55-11e5-9a39-005056c00008 +2d4324e3-0f55-11e5-afa4-005056c00008 +2d4324e4-0f55-11e5-b056-005056c00008 +2d4324e5-0f55-11e5-b9aa-005056c00008 +2d4324e6-0f55-11e5-be9f-005056c00008 +2d4324e7-0f55-11e5-bb63-005056c00008 +2d4324e8-0f55-11e5-9953-005056c00008 +2d4324e9-0f55-11e5-b38a-005056c00008 +2d4324ea-0f55-11e5-b6c3-005056c00008 +2d4324eb-0f55-11e5-8263-005056c00008 +2d4324ec-0f55-11e5-9614-005056c00008 +2d4324ed-0f55-11e5-adac-005056c00008 +2d4324ee-0f55-11e5-b14c-005056c00008 +2d4324ef-0f55-11e5-9b03-005056c00008 +2d4324f0-0f55-11e5-b170-005056c00008 +2d4324f1-0f55-11e5-a4c5-005056c00008 +2d4324f2-0f55-11e5-8339-005056c00008 +2d4324f3-0f55-11e5-9e09-005056c00008 +2d4324f4-0f55-11e5-9f87-005056c00008 +2d4324f5-0f55-11e5-b5d5-005056c00008 +2d4324f6-0f55-11e5-bdda-005056c00008 +2d4324f7-0f55-11e5-a302-005056c00008 +2d4324f8-0f55-11e5-9cfc-005056c00008 +2d4324f9-0f55-11e5-bf30-005056c00008 +2d434bcf-0f55-11e5-b117-005056c00008 +2d434bd0-0f55-11e5-9677-005056c00008 +2d434bd1-0f55-11e5-9433-005056c00008 +2d434bd2-0f55-11e5-a0a9-005056c00008 +2d434bd3-0f55-11e5-80e1-005056c00008 +2d434bd4-0f55-11e5-a504-005056c00008 +2d434bd5-0f55-11e5-9d0e-005056c00008 +2d434bd6-0f55-11e5-afd2-005056c00008 +2d434bd7-0f55-11e5-a37b-005056c00008 +2d434bd8-0f55-11e5-8ac6-005056c00008 +2d434bd9-0f55-11e5-b15d-005056c00008 +2d434bda-0f55-11e5-9adf-005056c00008 +2d434bdb-0f55-11e5-a36b-005056c00008 +2d434bdc-0f55-11e5-adaa-005056c00008 +2d434bdd-0f55-11e5-b1f0-005056c00008 +2d434bde-0f55-11e5-b3e3-005056c00008 +2d434bdf-0f55-11e5-a63c-005056c00008 +2d434be0-0f55-11e5-a2bc-005056c00008 +2d434be1-0f55-11e5-9879-005056c00008 +2d434be2-0f55-11e5-a762-005056c00008 +2d434be3-0f55-11e5-960f-005056c00008 +2d434be4-0f55-11e5-a09d-005056c00008 +2d434be5-0f55-11e5-9ac9-005056c00008 +2d434be6-0f55-11e5-a32e-005056c00008 +2d434be7-0f55-11e5-be33-005056c00008 +2d434be8-0f55-11e5-9ce6-005056c00008 +2d434be9-0f55-11e5-89cc-005056c00008 +2d434bea-0f55-11e5-bfaf-005056c00008 +2d434beb-0f55-11e5-ba34-005056c00008 +2d434bec-0f55-11e5-9d7f-005056c00008 +2d434bed-0f55-11e5-ad4a-005056c00008 diff --git a/Silocean/0003/Test.py b/Silocean/0003/Test.py new file mode 100644 index 00000000..542a2a74 --- /dev/null +++ b/Silocean/0003/Test.py @@ -0,0 +1,10 @@ +# -*-coding:utf-8-*- +__author__ = 'Tracy' +import redis, uuid + +r = redis.StrictRedis(host='localhost', port=6379) +for i in range(200): + r.set('key_id'+str(i), uuid.uuid1()) + +for i in range(200): + print(r.get("key_id"+str(i))) \ No newline at end of file diff --git a/Silocean/0004/Test.py b/Silocean/0004/Test.py new file mode 100644 index 00000000..4955b1b9 --- /dev/null +++ b/Silocean/0004/Test.py @@ -0,0 +1,12 @@ +__author__ = 'Tracy' + +import io, re + +count = 0 + +with io.open('text.txt', 'r') as file: + for line in file.readlines(): + list = re.findall("[a-zA-Z]+'*-*[a-zA-Z]*", line) + count += len(list) +print(count) + diff --git a/Silocean/0004/text.txt b/Silocean/0004/text.txt new file mode 100644 index 00000000..2379c58b --- /dev/null +++ b/Silocean/0004/text.txt @@ -0,0 +1 @@ +The Dursleys had everything they wanted, but they also had a secret, and their greatest fear was that somebody would discover it. They didn't think they could bear it if anyone found out about the Potters. Mrs. Potter was Mrs. Dursley's sister, but they hadn't met for several years; in fact, Mrs. Dursley pretended she didn't have a sister, because her sister and her good-for-nothing husband were as unDursleyish as it was possible to be. The Dursleys shuddered to think what the neighbors would say if the Potters arrived in the street. The Dursleys knew that the Potters had a small son, too, but they had never even seen him. This boy was another good reason for keeping the Potters away; they didn't want Dudley mixing with a child like that. \ No newline at end of file diff --git a/Silocean/0005/Test.py b/Silocean/0005/Test.py new file mode 100644 index 00000000..a311f859 --- /dev/null +++ b/Silocean/0005/Test.py @@ -0,0 +1,19 @@ +# -*-coding:utf-8-*- +__author__ = 'Tracy' +import os +import Image + +path = 'images' + +for f in os.listdir(path): + img = Image.open(os.path.join(path, f)) + width = img.size[0] + height = img.size[1] + out = img + if width > 1136: + width = 1136 + out = img.resize((width, height), Image.ANTIALIAS) + if height > 640: + height = 640 + out = img.resize((width, height), Image.ANTIALIAS) + out.save('images/result/'+f) diff --git a/Silocean/0006/Test.py b/Silocean/0006/Test.py new file mode 100644 index 00000000..ae2b3f59 --- /dev/null +++ b/Silocean/0006/Test.py @@ -0,0 +1,27 @@ +# -*-coding:utf-8-*- +__author__ = 'Tracy' +import os,re + +path = 'diaries' +files = os.listdir(path) + +def get_key_word(words): + dic = {} + max = 0 + marked_key = '' + for word in words: + if dic.has_key(word) is False: + dic[word] = 1 + else: + dic[word] = dic[word] + 1 + for key, value in dic.items(): + if dic[key] > max: + max = dic[key] + marked_key = key + print(marked_key, max) + + +for f in files: + with open(os.path.join(path, f)) as diary: + words = re.findall("[a-zA-Z]+'*-*[a-zA-Z]*",diary.read()) + get_key_word(words) \ No newline at end of file diff --git a/Silocean/0006/diaries/day01.txt b/Silocean/0006/diaries/day01.txt new file mode 100644 index 00000000..be5fddd0 --- /dev/null +++ b/Silocean/0006/diaries/day01.txt @@ -0,0 +1,4 @@ +Python learning + +This is a diary about Python. +Python is an interesting language, which is very easy to learn and we can use it to do many things. \ No newline at end of file diff --git a/Silocean/0006/diaries/day02.txt b/Silocean/0006/diaries/day02.txt new file mode 100644 index 00000000..c2d743f7 --- /dev/null +++ b/Silocean/0006/diaries/day02.txt @@ -0,0 +1,2 @@ +Hello Java!!! +I love Java...... \ No newline at end of file diff --git a/Silocean/0006/diaries/day03.txt b/Silocean/0006/diaries/day03.txt new file mode 100644 index 00000000..202d770c --- /dev/null +++ b/Silocean/0006/diaries/day03.txt @@ -0,0 +1,9 @@ +The Dursleys had everything they wanted, but they also had a secret, +and their greatest fear was that somebody would discover it. + They didn't think they could bear it if anyone found out about the Potters. + Mrs. Potter was Mrs. Dursley's sister, but they hadn't met for several years; + in fact, Mrs. Dursley pretended she didn't have a sister, because her sister and her good-for-nothing + husband were as unDursleyish as it was possible to be. + The Dursleys shuddered to think what the neighbors would say if the Potters arrived in the street. + The Dursleys knew that the Potters had a small son, too, but they had never even seen him. + This boy was another good reason for keeping the Potters away; they didn't want Dudley mixing with a child like that \ No newline at end of file diff --git a/Silocean/0007/Test.py b/Silocean/0007/Test.py new file mode 100644 index 00000000..7c09b4db --- /dev/null +++ b/Silocean/0007/Test.py @@ -0,0 +1,39 @@ +__author__ = 'Tracy' + +import os, io, re + +commentLines = 0 +whiteLines = 0 +comment = False + +path = 'F:\AllKindsOfWorkplace\PyCharmWorkplace\PythonLearning' + +count = 0 +def tree(path): + filelist = os.listdir(path) + for file in filelist: + if os.path.isdir(os.path.join(path, file)): + tree(os.path.join(path, file)) + else: + filename = os.path.basename(os.path.join(path, file)) + if filename.endswith(".py"): + # print(filename) + file = io.open(os.path.join(path, file)) + parse(file) + file.close() + +def parse(file): + global commentLines + global whiteLines + global comment + for line in file.readlines(): + # line = line.strip("\n") + if line.startswith("#"): + commentLines += 1 + elif re.match("^[\\s&&[^\\n]]*$", line): + whiteLines += 1 + +tree(path) + +print(commentLines) +print(whiteLines) diff --git a/Silocean/0008/Test.html b/Silocean/0008/Test.html new file mode 100644 index 00000000..17e2b30a --- /dev/null +++ b/Silocean/0008/Test.html @@ -0,0 +1,17 @@ + + + + +This is the Title + + + +
+ + + +{% endif %} + + +
+ + + + + diff --git a/llluiop/0023/MyDjango/templates/index.html b/llluiop/0023/MyDjango/templates/index.html new file mode 100644 index 00000000..bbdd67cb --- /dev/null +++ b/llluiop/0023/MyDjango/templates/index.html @@ -0,0 +1,86 @@ +{% load staticfiles %} + + + + + + + + + + + Starter Template for Bootstrap + + + + + + + + + + + + + + + + + + + + +
+ +
+

Bootstrap starter template

+

Use this document as a way to quickly start any new project.
All you get is this text and a mostly barebones HTML document.

+
+ + + +
+ + + + + + + + + + diff --git a/llluiop/0023/MyDjango/web/__init__.py b/llluiop/0023/MyDjango/web/__init__.py new file mode 100644 index 00000000..e69de29b diff --git a/llluiop/0023/MyDjango/web/admin.py b/llluiop/0023/MyDjango/web/admin.py new file mode 100644 index 00000000..a2c155b9 --- /dev/null +++ b/llluiop/0023/MyDjango/web/admin.py @@ -0,0 +1,10 @@ +from django.contrib import admin + +# Register your models here. +from models import Person + +class PersonAdmin(admin.ModelAdmin): + list_display = ('name', 'age') + +#admin.site.register(Person) +admin.site.register(Person, PersonAdmin) diff --git a/llluiop/0023/MyDjango/web/migrations/0001_initial.py b/llluiop/0023/MyDjango/web/migrations/0001_initial.py new file mode 100644 index 00000000..81573ccf --- /dev/null +++ b/llluiop/0023/MyDjango/web/migrations/0001_initial.py @@ -0,0 +1,21 @@ +# -*- coding: utf-8 -*- +from __future__ import unicode_literals + +from django.db import migrations, models + + +class Migration(migrations.Migration): + + dependencies = [ + ] + + operations = [ + migrations.CreateModel( + name='Person', + fields=[ + ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), + ('name', models.CharField(max_length=30)), + ('age', models.IntegerField()), + ], + ), + ] diff --git a/llluiop/0023/MyDjango/web/migrations/0002_message.py b/llluiop/0023/MyDjango/web/migrations/0002_message.py new file mode 100644 index 00000000..63d075ec --- /dev/null +++ b/llluiop/0023/MyDjango/web/migrations/0002_message.py @@ -0,0 +1,23 @@ +# -*- coding: utf-8 -*- +from __future__ import unicode_literals + +from django.db import migrations, models + + +class Migration(migrations.Migration): + + dependencies = [ + ('web', '0001_initial'), + ] + + operations = [ + migrations.CreateModel( + name='Message', + fields=[ + ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), + ('name', models.CharField(max_length=30)), + ('text', models.CharField(max_length=255)), + ('date', models.DateTimeField(auto_now_add=True)), + ], + ), + ] diff --git a/llluiop/0023/MyDjango/web/migrations/__init__.py b/llluiop/0023/MyDjango/web/migrations/__init__.py new file mode 100644 index 00000000..e69de29b diff --git a/llluiop/0023/MyDjango/web/models.py b/llluiop/0023/MyDjango/web/models.py new file mode 100644 index 00000000..88431220 --- /dev/null +++ b/llluiop/0023/MyDjango/web/models.py @@ -0,0 +1,16 @@ +from django.db import models + +# Create your models here. + +class Person(models.Model): + name = models.CharField(max_length=30) + age = models.IntegerField() + + def __unicode__(self): + return self.name + + +class Message(models.Model): + name = models.CharField(max_length=30) + text = models.CharField(max_length=255) + date = models.DateTimeField(auto_now_add=True) diff --git a/JiYouMCC/0024/todoList/todoList/list/tests.py b/llluiop/0023/MyDjango/web/tests.py similarity index 100% rename from JiYouMCC/0024/todoList/todoList/list/tests.py rename to llluiop/0023/MyDjango/web/tests.py diff --git a/llluiop/0023/MyDjango/web/views.py b/llluiop/0023/MyDjango/web/views.py new file mode 100644 index 00000000..63059e41 --- /dev/null +++ b/llluiop/0023/MyDjango/web/views.py @@ -0,0 +1,48 @@ +from django.shortcuts import render + +# Create your views here. +from django.http import HttpResponse +from django.http import HttpResponseRedirect +from django.core.urlresolvers import reverse +from models import Person +from models import Message +import datetime + +def current_time(request): + now = datetime.datetime.now() + + html = "It is now %s." % now + + return HttpResponse(html) + + +def add(request, a, b): + c = int(a) + int(b) + + return HttpResponse(c) + + +def home(request): + return render(request, 'index.html') + +def person(request): + name = 'person in table are:' + for p in Person.objects.all(): + name += p.name + + return HttpResponse(name) + +def board(request): + messages = Message.objects.all() + content = {'messages': messages} + return render(request, 'board.html', content) + + +def postmessage(request): + name = request.POST['name'] + text = request.POST['text'] + + m = Message(name=name, text=text) + m.save() + + return HttpResponseRedirect(reverse('board')) diff --git a/lulujianjie/0000/0000.py b/lulujianjie/0000/0000.py new file mode 100644 index 00000000..2c2f4b1d --- /dev/null +++ b/lulujianjie/0000/0000.py @@ -0,0 +1,17 @@ +from PIL import Image, ImageDraw, ImageFont + +im = Image.open('image.jpg') +w,h = im.size +font_size = h/4 + +draw = ImageDraw.Draw(im) +fnt = ImageFont.truetype ("Arial.ttf",font_size) + +text_w,text_h = draw.textsize("8",font=fnt) # 给定文字message,返回所占像素(width,height) + +draw.text((w-text_w,0), "8", fill=(255,0,0), font=fnt)#图片宽度减去字体宽度、要写的字符、颜色、字体 + + +im.save('image_1.jpg') + +#reference http://www.cnblogs.com/wei-li/archive/2012/04/19/2456725.html \ No newline at end of file diff --git a/lulujianjie/0000/Thumbs.db b/lulujianjie/0000/Thumbs.db new file mode 100644 index 00000000..c5f2ca42 Binary files /dev/null and b/lulujianjie/0000/Thumbs.db differ diff --git a/lulujianjie/0001/0001.py b/lulujianjie/0001/0001.py new file mode 100644 index 00000000..1343ddf9 --- /dev/null +++ b/lulujianjie/0001/0001.py @@ -0,0 +1,8 @@ +import uuid + +uuids = [] +for i in range(200):#0-199 + uuids.append(uuid.uuid1())#append把value当作一个整体插入list +i = 0; + for i in range(200): + print uuids[i] diff --git a/lulujianjie/0004/0004.py b/lulujianjie/0004/0004.py new file mode 100644 index 00000000..08870c8c --- /dev/null +++ b/lulujianjie/0004/0004.py @@ -0,0 +1,29 @@ +import re +lines_count = 0 +#words_count = 0 +chars_count = 0 +lines_list = [] +words_list = {} +with open('./test.txt','r') as f: +#http://www.liaoxuefeng.com/wiki/001374738125095c955c1e6d8bb493182103fac9270762a000/001386820066616a77f826d876b46b9ac34cb5f34374f7a000 + for line in f:## ʹļ , ÿֻȡʾһ +#http://blog.csdn.net/mvpme82/article/details/5674200 + lines_count += 1 + chars_count += len(line)#ո +#ʽhttp://www.liaoxuefeng.com/wiki/001374738125095c955c1e6d8bb493182103fac9270762a000/001386832260566c26442c671fa489ebc6fe85badda25cd000 + lines_list = re.findall(r'[a-zA-Z\-]+',line) + print lines_list + for i in lines_list: + #words_count += 1 + if i not in words_list: + words_list[i] = 1 + else: + words_list[i] += 1 + + print 'lines_count:',lines_count + print 'chars_count:',chars_count + print 'words_count:',len(words_list)#ֵԪظ + +for word,quantity in words_list.items(): + print word,'\'s number is ',quantity + ## f.close() diff --git a/lulujianjie/0004/test.txt b/lulujianjie/0004/test.txt new file mode 100644 index 00000000..a8d88698 --- /dev/null +++ b/lulujianjie/0004/test.txt @@ -0,0 +1,13 @@ +hello world! +lujianjie +### +ksdfksdkk*& +ljj-wyj + +lujianjie +### +ksdfksdkk*& +ljj-wyj lujianjie +### +ksdfksdkk*& +ljj-wyj \ No newline at end of file diff --git a/lwh/0/addnum.py b/lwh/0/addnum.py new file mode 100644 index 00000000..b1786382 --- /dev/null +++ b/lwh/0/addnum.py @@ -0,0 +1,18 @@ +from PIL import Image, ImageDraw +from PIL import ImageFont +import random + +# 设置字体 +font = ImageFont.truetype("C:/Windows/Fonts/Arial.ttf", 20) + +#打开文件 +im = Image.open("avatar.jpg") + +#使用PIl的ImageDraw +draw = ImageDraw.Draw(im) +text = str(random.randint(1, 20)) +point = (180, 10) +draw.text(point, text, font=font, fill="red") + +#保存 +im.save("avatar2.jpg") diff --git a/lwh/0/avatar.jpg b/lwh/0/avatar.jpg new file mode 100644 index 00000000..e2710c9c Binary files /dev/null and b/lwh/0/avatar.jpg differ diff --git a/lwh/1/active_code.py b/lwh/1/active_code.py new file mode 100644 index 00000000..4edfee9f --- /dev/null +++ b/lwh/1/active_code.py @@ -0,0 +1,25 @@ +""" +做为 Apple Store App 独立开发者,你要搞限时促销, +为你的应用生成激活码(或者优惠券), +使用 Python 如何生成 200 个激活码(或者优惠券)? + +激活码格式: +19个字符组成,分成4组,中间用"-"连接起来 +必须同时包含大小写字母数字 + +""" +import random +import string + + +def generate_active_code(): + active_code = [] + ascii_ = string.ascii_letters + string.digits + active_code = ["".join([random.choice(ascii_) for i in range(16)]) + for j in range(200)] + print(len(active_code)) + return active_code + +if __name__ == "__main__": + active_code = generate_active_code() + print(active_code) diff --git a/lwh/10/captcha.jpg b/lwh/10/captcha.jpg new file mode 100644 index 00000000..e74e2a31 Binary files /dev/null and b/lwh/10/captcha.jpg differ diff --git a/lwh/10/captcha.py b/lwh/10/captcha.py new file mode 100644 index 00000000..3c7b8572 --- /dev/null +++ b/lwh/10/captcha.py @@ -0,0 +1,34 @@ +""" + 生成图片验证码 +""" +import PIL +import string +import random +from PIL import Image, ImageDraw, ImageFont, ImageFilter + +image_path = "C:\\Users\\lwhil\\Desktop\\captcha.jpg" +save_path = "C:\\Users\\lwhil\\Desktop\\captcha_f.jpg" +font = ImageFont.truetype("C:/Windows/Fonts/Arial.ttf", 60) +color = ["red", "black", "green", "blue", "yellow"] +letters = string.ascii_letters + + +def generate_captcha(): + image = Image.open(image_path) + draw = ImageDraw.Draw(image) + for i in range(1, 6): + nums = str(random.randint(0, 9)) + width, height = image.size + print(width, height) + point = (50 + i * 100, 200 + random.randint(-100, 100)) + draw.text(point, nums, font=font, fill=color[random.randint(0, 4)]) + # image.rotate(90) #文档只有整张图片的倾斜效果,效果不好,不如不要 + + # 产生模糊效果 + GaussBlur = ImageFilter.GaussianBlur(radius=5) + image = image.filter(GaussBlur) + + image.save(save_path) + +if __name__ == "__main__": + generate_captcha() diff --git a/lwh/10/captcha_f.jpg b/lwh/10/captcha_f.jpg new file mode 100644 index 00000000..9dd466ef Binary files /dev/null and b/lwh/10/captcha_f.jpg differ diff --git a/lwh/11/filter_word.py b/lwh/11/filter_word.py new file mode 100644 index 00000000..dcbac77d --- /dev/null +++ b/lwh/11/filter_word.py @@ -0,0 +1,42 @@ +# coding = utf-8 +""" +def filter_word(): + + # init + filter_words_list = [] + with open("filtered_words.txt", "r") as f: + string_read = f.readline() + while string_read != "": + filter_words_list.append(string_read) + string_read = f.readline() + + print("Enter \\q to exit.") + string_input = input( + "Input your word to check whether it was filtered ->") + while string_input != "\\q": + if string_input in filter_words_list: + print("Freedom") + else: + print("Human Rights") + string_input = input( + "Input your word to check whether it was filtered ->") + +if __name__ == "__main__": + filter_word() + +""" +# coding = utf-8 +__author__ = 'Forec' +word_filter = set() +with open('filtered_words.txt',"r") as f: + for x in f.readlines(): + word_filter |= {x.rstrip('\n')} +while True: + s = input() + if s == 'exit': + break + elif s in word_filter: + print('Freedom') + else: + print('Human Rights') + \ No newline at end of file diff --git a/lwh/11/filtered_words.txt b/lwh/11/filtered_words.txt new file mode 100644 index 00000000..444eb7c6 --- /dev/null +++ b/lwh/11/filtered_words.txt @@ -0,0 +1,11 @@ + +Ա +Ա +쵼 +ţ +ţ + + +love +sex +jiangge \ No newline at end of file diff --git a/lwh/12/demo.txt b/lwh/12/demo.txt new file mode 100644 index 00000000..1b4f2244 --- /dev/null +++ b/lwh/12/demo.txt @@ -0,0 +1,11 @@ +北京 +程序员 +公务员 +领导 +牛比 +牛逼 +你娘 +你妈 +love +sex +jiangge diff --git a/lwh/12/filter.py b/lwh/12/filter.py new file mode 100644 index 00000000..d90889aa --- /dev/null +++ b/lwh/12/filter.py @@ -0,0 +1,31 @@ +import re +import string + + +class Filter(object): + + def __init__(self): + self.filtered_word_list = [] + self.readIO() + + def check(self, word_input): + res = word_input + for e in self.filtered_word_list: + # print(e) + if e in word_input: + res = res.replace(e, '*' * len(e)) + return res + + def readIO(self): + with open('demo.txt', 'r') as f: + s_temp = f.readline().strip() + while s_temp != "": + self.filtered_word_list.append(s_temp) + s_temp = f.readline().strip() + +if __name__ == "__main__": + filter_obj = Filter() + while True: + word_input = input("Enter a sentence to check >") + str_ans = filter_obj.check(word_input) + print(str_ans) diff --git a/lwh/14/SaveToExcel.py b/lwh/14/SaveToExcel.py new file mode 100644 index 00000000..7e82904e --- /dev/null +++ b/lwh/14/SaveToExcel.py @@ -0,0 +1,43 @@ +from openpyxl import Workbook +from openpyxl import load_workbook + +path_save = "/home/lwh/SublimeTextProject/test.xlsx" +path_read = "/home/lwh/SublimeTextProject/demo.txt" + + +def write_test(): + wb = Workbook() # 1.creat a work book + wb_sheet0 = wb.create_sheet("student") # 2.create a sheet in the work book + + datas_str = "" + datas_dict = {} + + with open(path_read, "r") as f: + lines = f.readlines() + + # process the data from txt file.I make it be a dict + for line in lines: + if len(line.strip()) > 1: + key, value = line.split(':') + key = key.strip().strip("\"") + value = value.strip().strip(",").strip("[").strip("]") + value_list = value.split(",") + # print(len(value_list)) + datas_dict[key] = value_list + + for i in range(1, 4): # 3.assign value to cell of the sheet + for j in range(1, 5): + cell = wb_sheet0.cell(row=i, column=j + 1) + cell.value = datas_dict[str(i)][j - 1] + # print(cell.value) + cell = wb_sheet0.cell(row=i, column=1) + cell.value = i + ''' + for row in wb_sheet0.iter_rows(): + for cell in row: + print(cell.value) + ''' + wb.save(path_save) # 4.save the file + print('success') + +write_test() diff --git a/lwh/14/demo.txt b/lwh/14/demo.txt new file mode 100644 index 00000000..1c4ffe6d --- /dev/null +++ b/lwh/14/demo.txt @@ -0,0 +1,5 @@ +{ + "1":["张三",150,120,100], + "2":["李四",90,99,95], + "3":["王五",60,66,68] +} diff --git a/lwh/14/demo.txt~ b/lwh/14/demo.txt~ new file mode 100644 index 00000000..e69de29b diff --git a/lwh/17/demo.txt b/lwh/17/demo.txt new file mode 100644 index 00000000..ea9b1593 --- /dev/null +++ b/lwh/17/demo.txt @@ -0,0 +1,5 @@ +{ + "1":["张三",150,120,100], + "2":["李四",90,99,95], + "3":["王五",60,66,68] +} \ No newline at end of file diff --git a/lwh/17/test.xlsx b/lwh/17/test.xlsx new file mode 100644 index 00000000..51718fa1 Binary files /dev/null and b/lwh/17/test.xlsx differ diff --git a/lwh/17/xlxs_to_xml.py b/lwh/17/xlxs_to_xml.py new file mode 100644 index 00000000..a5b2530c --- /dev/null +++ b/lwh/17/xlxs_to_xml.py @@ -0,0 +1,53 @@ +from xml.etree.ElementTree import ElementTree, Element, SubElement, Comment +from openpyxl import load_workbook +import json +from pprint import pprint + + +class ExcelToXml(object): + + def __init__(self): + self.path_save = '/home/lwh/SublimeTextProject/test.xml' + self.path_read = '/home/lwh/SublimeTextProject/test.xlsx' + self.excel_dict = self.get_excel_dict() + self.data = self.get_text(self.excel_dict) + self.xml_final = self.get_xml(self.data) + self.save_xml(self.xml_final) + + def get_excel_dict(self): + wb = load_workbook(self.path_read) + wb_sheet_student = wb['student'] + excel_dict = {} + for row in wb_sheet_student.iter_rows(): + key = str(row[0].value).strip() + value_list = row[1:] + value = [ele.value for ele in value_list] + excel_dict[key] = str(value) + return excel_dict + + def get_text(self, excel_dict): + res = '{\r\n' + for key, val in excel_dict.items(): + res += ' ' + str(key) + ':' + val + '\n' + res += '}\n' + # print(res) + return res + + def get_xml(self, data): + root = Element('root') + student = SubElement(root, 'students') + student.append(Comment('学生信息表 "id" : [名字, 数学, 语文, 英文]')) + # student. + print(data) + student.text = data + xml_final = ElementTree(root) + # print(xml_final) + return xml_final + + def save_xml(self, xml_to_save): + xml_to_save.write( + self.path_save, encoding="us-ascii", default_namespace=None, short_empty_elements=True) + + +if __name__ == '__main__': + excel_to_xml_obj = ExcelToXml() diff --git a/lwh/2/active_code.py b/lwh/2/active_code.py new file mode 100644 index 00000000..6679a15d --- /dev/null +++ b/lwh/2/active_code.py @@ -0,0 +1,25 @@ +""" +做为 Apple Store App 独立开发者,你要搞限时促销, +为你的应用生成激活码(或者优惠券), +使用 Python 如何生成 200 个激活码(或者优惠券)? + +激活码格式: +19个字符组成,分成4组,中间用"-"连接起来 +必须同时包含大小写字母数字 + +""" +import random +import string + + +def generate_active_code(): + active_code = [] + ascii_ = string.ascii_letters + string.digits + active_code = ["".join([random.choice(ascii_) for i in range(16)]) + for i in range(200)] + + return active_code + +if __name__ == "__main__": + active_code = generate_active_code() + print(active_code) diff --git a/lwh/2/active_code.txt b/lwh/2/active_code.txt new file mode 100644 index 00000000..d07d57cc --- /dev/null +++ b/lwh/2/active_code.txt @@ -0,0 +1,200 @@ +RXUadiI0zOKmg5Ww +z4qo5vaXKGM8uFsB +TU3PdPnSAKtUcXwl +dy2nuUEjRczyXC0a +Xn8MFsTBRCbcG45E +7DmryUic3pOs1DFu +REINIyXEsovPrJ2G +OKTYjXVpTljHanCO +SzsuRGUmL6sEXBA1 +FrKGmMjKQGt0ImDV +BLYXVaqENcuJXfUh +ydsilfQorQtLKJs4 +abX1AUFy61k0gPZh +xjEyzBwwu9AXrAaU +wuJXMMscjhUpjOu1 +fbVRxeWbpilOQEQ2 +gKnLlSMvzFup2ubi +mcU54YoHxGZ3gbRy +izdNk0U2nlAqN5HT +zGx1bP240lai9qMG +3Nqa5IB5dzuPWfBA +jAtgS3XXojFlWI5j +L8rb8ODGhGO03D7x +1SZ5ouRlwulVMcVd +jGr71Sx2eU1BTzvq +sB24ocOCXxuUwvJg +RHesYESjimTftYZA +gJvEvwB7nlRnsmcQ +hVa1H4Ig9VfzBmRz +bEGSjiMZMWpeRyhy +3mFUtX6T3q6qJmN1 +jfKbj7WEu7LuBjw8 +07qBOuEyTvsoeC7o +JCAGJusp8qdr7NzD +5vrE1vhHIJ4rqLcU +PquV3EUuOWDTy4pX +ZEEcNm4o7JXQuRZn +xDGpAt5uUHbi3HLN +7KtkUMfREmSdTebQ +4CTfOxmFFT7VX6Ha +hWFdJW034cEKX8nT +vgaQuZgmOWeBdBHr +iZsJpE4eSh7ZqgYq +bX3Wf9ya2AYB0Ek5 +7dAQNjyHPJ3BKTmt +yCCVEeAAXwmPjj7x +zt4Y1ptPZmFMEQ7Y +TNXXk5PE2dKJTKwY +qClONH4dhtpblVxO +BcOxR9eik1YcKAIt +IxVcoCfhx5U1KhJL +e6LgwfakF5sIo3Wn +rBz6ifzKMmLjRqnr +7sG7zoOEjwiPVwMN +2SpgY4eExdqyFma9 +seIIcsNT0deljKcF +jUY48NLHJWn5mjSm +epNdFfnUy3K9tddV +FLKdZilBUpYloqLH +b4flf5wi6a4joQwA +1hJ2tGTJwlvgjebQ +KW0W8x23QRAQMC3K +tvOBXdSFbujyiLnl +9SygR3CYo4ReQ1x4 +rTcggxAwbuu7waNy +ql4gqiS3kJuNexrl +ZpmKF1VYeIbvrAwE +NhW0mMDUX9j1QkOR +VHKBmzABwLwH1c8Y +238sBuP3YIJJIUn6 +EyLVxAOASe5PWDsi +BDxWOvKpe3FRHfXZ +qkqz0lD4ogDgG6HB +I8M1aVJCRc2452OG +JWl7JmPKK9sq8v2r +bdXCjhrHUSNXsNPJ +sEcmFMdcvz57wBkr +OYouRL6AD21NncGn +aNRk1zxXhrr30fAm +g40yzH8LHOOymofr +oPw8MO6iNamJ1bYK +QfnffjYdbE8BKCqF +mbEKxuHBNHHloDy0 +oeVHq1yblfNbDlm2 +S5O9WOvWHMUU0ymx +eiwlpN9GuRGmpbn0 +TMGHVairDKmSGbCk +kiOC0MLXtctQxLe5 +rfoaB5W9YxwMzNki +FWIoPqzYBkxWUA5n +HoCqNcTtQEtjAUMP +Gy6nVQJmgsgv9hGc +PBTm3QAQ6jNFkvUZ +j3yRTRrcFGUgDwow +bPF8g0RHaN47Q4dN +NzM9WIrXiDbi5IXD +w54j8L5ngiakgayX +hkd4g0UkVhmNnyR6 +iEz5VpcVi1mpS1gq +KWkIIA97y42V5cnx +5LZGIXk2odGvSTE1 +s1NdaGmS5YB8VJEL +272uuYgOloY7hJ8t +oc0hco4FYw75n4US +DzmWY32kG7JaFG3R +UIaLpcjN9yA12Uo5 +8RYmqxQ8IxUU0aGz +D5Td2B7lEEUDYsUw +vJ0rZHnIlI6sHDo5 +MYLBHHfax5MvUf96 +CQisO7bfEUwpr2Qy +dyLBeumYaTAGHFyM +wvFS79uJMwWSUgHv +KkwuShhSHkzKy6op +O72zwUdEuetJnnQ6 +Qj7r8dbBf1fKV55k +T7K47FF9KcrEYcI7 +N79n066wlGUsxanD +XPrc3XrLHA23mmmb +sANdjXf4gD5tJvWF +ARJPiZz9HmQbtqOW +7WAr9oIw9sebBNWj +UmKbDJ9Z3XDB0uxa +XbqEHERAPrrM42ud +iRMKgFM0gqr9G8Rt +WfdEyO5sGxXKiYND +3hPPrf7M3UPk3Pis +PiL0B8e9ZtKPRsuj +YuQXWQTw24RlfOUw +nG8kOk3G6VWM3XcX +0XblQUEM8uCl8ljl +VY2AKbDNFTXT2Vpj +BZkiI7LxBsSPp9wI +WuCVLSQqpj2jBA74 +I6ASBeIdmYPxg7Zx +OIAeCY1FHbOdJHnk +h3r45aQva46D0MkG +BlHBdOq3KqcokYnp +X4mFpYkR7LgyBdf9 +r04TZnPIpXlrYajl +Zoa59BtKi0C7N3vQ +PAUVrdCcV46DMcTa +XzkP2UjLVPd6UdeH +tFuOwhfZAminRknq +LLRXDREtywZ9oL2l +1Bt1hjCu87iRvjVO +843udSQ5CYhxzpY3 +zm78Qr1fm6YbD5Pc +nkKKOAThEvmvMDck +daNI9lwDGwWPXgDh +3AD5vzwEgCh62OGG +g0WACS40VWUhhO3n +8DSPNQnnPpExp5ae +1qDbOw7VXQu6sJyx +IHeAepe22BqzyRYI +Pyc8MoGTBonXrsig +caIx6iJTzzrwRh76 +TuCiIBooXAtxGA1s +d5vL89dwRziYYkOC +Th7QNxgmuAHgdxjY +Qde8adGqOCJLStgi +X4YVCKnkpIglPXNH +DJaSfz6ZZ5AexZrh +p0suRQkjR2gPB50J +Xu7zNDMf8LTXgUfP +iO7lZE1d5u9C4agr +ZScUrgefG4mhv7sn +cxKn0LeiJmTmOncc +MlHM9bSCqbLeYQyl +hnNxbuM0iFXasDNU +U9TDcgewoYmCuL8Z +NiWuD6W6yo5naWVa +6xB2tyGaP9XD1Reu +MyMQgM3LVp3OOZbH +GNReq9Tsm9yEkjnH +wv0m9rGnQlTzWBsz +VXdYlEkAdRsw74Q6 +KYvyofRRw4HdHdGa +feOc882CM6u3Vmb9 +bHfFtp2xlqR9ov7Z +I9WJT51PDOho07f2 +mbfys9pZlaBa71fn +Z7B8uUPNGUolHgve +CyGhoq3E5eaLuYd8 +Sp4zPGY0Zb4ce2kX +dawy36RyxYpGlDTG +gJlcfSukZBZZbOji +DM5lIjwwSR5Ixta0 +HQIN6iSuBBu95Cy1 +c3JKxSbY0vqx4SEC +9H4DXpc17vFjPCeE +c48hIoAA5E5lVScv +gadG0fAunAWg3C4I +jr9kg1rr4rGPAT5i +aLipX2YqYy8FyImJ +GP87sr1igGhbAVnB +Oghe3rzJSi4N9bCh +j0pl6r1H8LD89zpg +g9G0cNNlbgRRiuRM +jqyltqFWJLEe0Gez diff --git a/lwh/2/pymysql.py b/lwh/2/pymysql.py new file mode 100644 index 00000000..a9cc1004 --- /dev/null +++ b/lwh/2/pymysql.py @@ -0,0 +1,39 @@ +# -*- coding: utf-8 -*- + +#!/usr/bin/python +# -*- coding: UTF-8 -*- + +import pymysql + + +# 打开数据库连接 +db = pymysql.connect("localhost", "root", "", "") + +# 使用cursor()方法获取操作游标 +cursor = db.cursor() + +# 使用execute方法执行SQL语句 +cursor.execute("CREATE DATABASE IF NOT EXISTS pymysql;") +cursor.execute("USE pymysql;") +cursor.execute( + "CREATE TABLE IF NOT EXISTS active_code(code VARCHAR(255));") + +with open("active_code.txt", "r") as f: + while True: + s = f.readline().strip() + # print(s) + if s == "": + break + cursor.execute("INSERT INTO active_code (code) values(%s)", [s]) + +db.commit() +#cursor.execute("USE pymsql") +cursor.execute("SELECT * FROM active_code") + +# 使用 fetchone() 方法获取一条数据库。 +#data = cursor.fetchone() + +#print("Database version : %s " % data) + +# 关闭数据库连接 +db.close() diff --git a/lwh/20/CallInfo.xls b/lwh/20/CallInfo.xls new file mode 100644 index 00000000..34826bb7 Binary files /dev/null and b/lwh/20/CallInfo.xls differ diff --git a/lwh/20/callinfo.py b/lwh/20/callinfo.py new file mode 100644 index 00000000..8ca4fa0b --- /dev/null +++ b/lwh/20/callinfo.py @@ -0,0 +1,81 @@ +import xlrd +import xlwt + + +class Statistics(object): + + def __init__(self, user): + self.path_read = '/home/lwh/SublimeTextProject/CallInfo.xls' + self.path_save = '/home/lwh/SublimeTextProject/CallInfo(1).xls' + self.user = user + self.work() + + # change all format of time to second + def tran_time(self, time_str): + time = time_str.replace('分', '.').replace('秒', '') + temp = time.split('.') + if len(temp) == 1: # just second + time = int(temp[0]) + # print(time) + elif len(temp) == 2: # minute and second + m = int(temp[0]) * 60 + s = int(temp[1]) + time = m + s + # print(time) + return time + + def work(self): + wb = xlrd.open_workbook(self.path_read) + sheets_list = wb.sheet_names() + for sheet_name in sheets_list: + wb_sheet = wb.sheet_by_name(sheet_name) + # print(wb_sheet) + # print(wb_sheet.nrows) + # print(wb_sheet.ncols) + # print(wb_sheet.cell_value(3,8)) + for i in range(1, wb_sheet.nrows): + row = wb_sheet.row(i) + + # time + time_str = row[3].value + time = self.tran_time(time_str) + self.user.total_time += time + + # calling info + in_or_out = row[4].value + if in_or_out == '被叫': + number_in = row[5].value + if number_in not in self.user.number_in_dict: + self.user.number_in_dict[number_in] = 0 + else: + self.user.number_in_dict[number_in] += 1 + elif in_or_out == '主叫': + number_out = row[5].value + if number_out not in self.user.number_out_dict: + self.user.number_out_dict[number_out] = 0 + else: + self.user.number_out_dict[number_out] += 1 + for key, val in self.user.number_in_dict.items(): + print('in', key, val) + for key, val in self.user.number_out_dict.items(): + print('out', key, val) + # print(self.user.total_time) + + +class User(): + + def __init__(self, name, num): + self.name = name + self.num = num + self.total_time = 0 + self.most_call_out = '' + self.most_call_in = '' + self.number_in_dict = {} + self.number_out_dict = {} + + +if __name__ == '__main__': + user0 = User('lwh', '13257584928') + analyzer_obj0 = Statistics(user0) + print('success.') + diff --git a/lwh/20/callinfo.py~ b/lwh/20/callinfo.py~ new file mode 100644 index 00000000..a00d58b0 --- /dev/null +++ b/lwh/20/callinfo.py~ @@ -0,0 +1,62 @@ +import xlrd +import xlwt + + +class Statistics(object): + + def __init__(self, user): + self.path_read = '/home/lwh/SublimeTextProject/CallInfo.xls' + self.path_save = '/home/lwh/SublimeTextProject/CallInfo(1).xls' + self.user = user + self.work() + + # change all format of time to second + def tran_time(self, time_str): + time = time_str.replace('分','.').replace('秒','') + temp = time.split('.') + if len(temp) == 1: # just second + time = int(temp[0]) + #print(time) + elif len(temp) == 2: # minute and second + m = int(temp[0]) * 60 + s = int(temp[1]) + time = m + s + #print(time) + return time + + + def work(self): + wb = xlrd.open_workbook(self.path_read) + sheets_list = wb.sheet_names() + for sheet_name in sheets_list: + wb_sheet = wb.sheet_by_name(sheet_name) + # print(wb_sheet) + # print(wb_sheet.nrows) + # print(wb_sheet.ncols) + # print(wb_sheet.cell_value(3,8)) + for i in range(1, wb_sheet.nrows): + row = wb_sheet.row(i) + time_str = row[3].value + time = self.tran_time(time_str) + self.user.total_time += time + # print(each_time) + # self.user.total_time = row[] + print(self.user.total_time) + +class User(): + + def __init__(self, name, num): + self.name = name + self.num = num + self.total_time = 0 + self.most_call_out = '' + self.most_call_in = '' + self.number_in_dict = '' + self.number_out_dict = '' + + +if __name__ == '__main__': + user0 = User('lwh', '13257584928') + analyzer_obj0 = Statistics(user0) + print('success.') + diff --git a/lwh/21/encrpyt.py b/lwh/21/encrpyt.py new file mode 100644 index 00000000..9d6ccaf3 --- /dev/null +++ b/lwh/21/encrpyt.py @@ -0,0 +1,24 @@ +from hashlib import sha256 +from hmac import HMAC +import os + + +class Encrypt(object): + + def encrypt(self, password, salt=None): + if salt is None: + salt = os.urandom(8) + result = password.encode('utf-8') + for i in range(10): + result = HMAC(result, salt, sha256).digest() + return salt + result + + def vaildate(self, password, hashed): + return hashed == self.encrypt(password, salt=hashed[:8]) + +if __name__ == '__main__': + obj = Encrypt() + hashed = obj.encrypt('wh5622') + # print(bytes.decode(hashed)) + ans = obj.vaildate('wh5622', hashed) + print(ans) diff --git a/lwh/23MessageBoard/app/__init__.py b/lwh/23MessageBoard/app/__init__.py new file mode 100644 index 00000000..b9357d3c --- /dev/null +++ b/lwh/23MessageBoard/app/__init__.py @@ -0,0 +1,5 @@ +from flask import Flask + +app = Flask(__name__) + +from app import views \ No newline at end of file diff --git a/lwh/23MessageBoard/app/models.py b/lwh/23MessageBoard/app/models.py new file mode 100644 index 00000000..e69de29b diff --git a/lwh/23MessageBoard/app/static/brand.ico b/lwh/23MessageBoard/app/static/brand.ico new file mode 100644 index 00000000..cde355d8 Binary files /dev/null and b/lwh/23MessageBoard/app/static/brand.ico differ diff --git a/lwh/23MessageBoard/app/static/brand.jpg b/lwh/23MessageBoard/app/static/brand.jpg new file mode 100644 index 00000000..e2710c9c Binary files /dev/null and b/lwh/23MessageBoard/app/static/brand.jpg differ diff --git a/lwh/23MessageBoard/app/templates/base.html b/lwh/23MessageBoard/app/templates/base.html new file mode 100644 index 00000000..a1d62872 --- /dev/null +++ b/lwh/23MessageBoard/app/templates/base.html @@ -0,0 +1,50 @@ + + + + + + + + + + + + + {% block content %} + {% endblock %} + + + + + + \ No newline at end of file diff --git a/lwh/23MessageBoard/app/templates/handlemessage.html b/lwh/23MessageBoard/app/templates/handlemessage.html new file mode 100644 index 00000000..d1992067 --- /dev/null +++ b/lwh/23MessageBoard/app/templates/handlemessage.html @@ -0,0 +1,4 @@ +{% extends 'base.html' %} +{% block content %} +

留言失败,未定义相关处理函数

+{% endblock %} \ No newline at end of file diff --git a/lwh/23MessageBoard/app/templates/index.html b/lwh/23MessageBoard/app/templates/index.html new file mode 100644 index 00000000..d12df5d6 --- /dev/null +++ b/lwh/23MessageBoard/app/templates/index.html @@ -0,0 +1,15 @@ +{% extends 'base.html' %} +{% block title %} +给lwh的留言板 +{% endblock %} +{% block content %} +
+ 名字: + +

+ 内容: + +

+
+ web + + + + +{% endblock %} + +{% block content %} +
+ {% for message in get_flashed_messages() %} +
+ + {{ message }} +
+ {% endfor %} + + {% block page_content %}{% endblock %} +
+{% endblock %} + +{% block scripts %} +{{ super() }} +{{ moment.include_moment() }} +{% endblock %} diff --git a/neo1218/0023/web/app/templates/index.html b/neo1218/0023/web/app/templates/index.html new file mode 100644 index 00000000..0be836c6 --- /dev/null +++ b/neo1218/0023/web/app/templates/index.html @@ -0,0 +1,25 @@ +{% extends "base.html" %} +{% import "bootstrap/wtf.html" as wtf %} + +{% block title %}web留言板{% endblock %} + +{% block page_content %} + +
+ {{ wtf.quick_form(form) }} +
+
+
    + {% for post in posts %} +
  • +
    + + +
    {{ post.body }}
    +
    +
  • + {% endfor %} +
+{% endblock %} diff --git a/neo1218/0023/web/config.py b/neo1218/0023/web/config.py new file mode 100644 index 00000000..c3ffa46e --- /dev/null +++ b/neo1218/0023/web/config.py @@ -0,0 +1,47 @@ +# -*- coding: UTF-8 -*- +# !/usr/bin/python + +# 配置文件 + +import os +basedir = os.path.abspath(os.path.dirname(__file__)) + + +class Config: + # 配置类 + SECRET_KEY = os.environ.get('SECRET_KEY') or 'hard to guess string' + SQLALCHEMY_COMMIT_ON_TEARDOWN = True + + @staticmethod + def init_app(app): + pass + + +class DevelopmentConfig(Config): + # 开发数据库 + DEBUG = True + SQLALCHEMY_DATABASE_URI = os.environ.get('DEV_DATABASE_URL') or \ + 'sqlite:///' + os.path.join(basedir, 'data-dev.sqlite') + + +class TestingConfig(Config): + # 测试数据库 + TESTING = True + SQLALCHEMY_DATABASE_URI = os.environ.get('TEST_DATABASE_URL') or \ + 'sqlite:///' + os.path.join(basedir, 'data-test.sqlite') + + +class ProductionConfig(Config): + # 生产数据库 + SQLALCHEMY_DATABASE_URI = os.environ.get('DATABASE_URL') or \ + 'sqlite:///' + os.path.join(basedir, 'data.sqlite') + + +config = { + 'development': DevelopmentConfig, + 'testing': TestingConfig, + 'production': ProductionConfig, + + 'default': DevelopmentConfig +} + diff --git a/neo1218/0023/web/data-dev.sqlite b/neo1218/0023/web/data-dev.sqlite new file mode 100644 index 00000000..cde0d075 Binary files /dev/null and b/neo1218/0023/web/data-dev.sqlite differ diff --git a/neo1218/0023/web/manage.py b/neo1218/0023/web/manage.py new file mode 100644 index 00000000..00d40d46 --- /dev/null +++ b/neo1218/0023/web/manage.py @@ -0,0 +1,39 @@ +# -*- coding: UTF-8 -*- +# !/usr/bin/python + +# 管理文件 + +import os +from app import create_app, db +from app.models import User +from flask.ext.script import Manager, Shell +from flask.ext.migrate import Migrate, MigrateCommand + +#-------------------设置编码格式----------------------- +import sys +reload(sys) +sys.setdefaultencoding('utf-8') +#------------------------------------------------------ + +app = create_app(os.getenv('FLASK_CONFIG') or 'default') +manager = Manager(app) +migrate = Migrate(app, db) + + +def make_shell_context(): + return dict(app=app, db=db, User=User) +manager.add_command("shell", Shell(make_context=make_shell_context)) +manager.add_command('db', MigrateCommand) + + +@manager.command +def test(): + """Run the unit tests.""" + import unittest + tests = unittest.TestLoader().discover('tests') + unittest.TextTestRunner(verbosity=2).run(tests) + + +if __name__ == '__main__': + manager.run() + diff --git a/neo1218/0023/web/migrations/README b/neo1218/0023/web/migrations/README new file mode 100644 index 00000000..98e4f9c4 --- /dev/null +++ b/neo1218/0023/web/migrations/README @@ -0,0 +1 @@ +Generic single-database configuration. \ No newline at end of file diff --git a/neo1218/0023/web/migrations/alembic.ini b/neo1218/0023/web/migrations/alembic.ini new file mode 100644 index 00000000..f8ed4801 --- /dev/null +++ b/neo1218/0023/web/migrations/alembic.ini @@ -0,0 +1,45 @@ +# A generic, single database configuration. + +[alembic] +# template used to generate migration files +# file_template = %%(rev)s_%%(slug)s + +# set to 'true' to run the environment during +# the 'revision' command, regardless of autogenerate +# revision_environment = false + + +# Logging configuration +[loggers] +keys = root,sqlalchemy,alembic + +[handlers] +keys = console + +[formatters] +keys = generic + +[logger_root] +level = WARN +handlers = console +qualname = + +[logger_sqlalchemy] +level = WARN +handlers = +qualname = sqlalchemy.engine + +[logger_alembic] +level = INFO +handlers = +qualname = alembic + +[handler_console] +class = StreamHandler +args = (sys.stderr,) +level = NOTSET +formatter = generic + +[formatter_generic] +format = %(levelname)-5.5s [%(name)s] %(message)s +datefmt = %H:%M:%S diff --git a/neo1218/0023/web/migrations/env.py b/neo1218/0023/web/migrations/env.py new file mode 100644 index 00000000..0a038e6c --- /dev/null +++ b/neo1218/0023/web/migrations/env.py @@ -0,0 +1,73 @@ +from __future__ import with_statement +from alembic import context +from sqlalchemy import engine_from_config, pool +from logging.config import fileConfig + +# this is the Alembic Config object, which provides +# access to the values within the .ini file in use. +config = context.config + +# Interpret the config file for Python logging. +# This line sets up loggers basically. +fileConfig(config.config_file_name) + +# add your model's MetaData object here +# for 'autogenerate' support +# from myapp import mymodel +# target_metadata = mymodel.Base.metadata +from flask import current_app +config.set_main_option('sqlalchemy.url', current_app.config.get('SQLALCHEMY_DATABASE_URI')) +target_metadata = current_app.extensions['migrate'].db.metadata + +# other values from the config, defined by the needs of env.py, +# can be acquired: +# my_important_option = config.get_main_option("my_important_option") +# ... etc. + + +def run_migrations_offline(): + """Run migrations in 'offline' mode. + + This configures the context with just a URL + and not an Engine, though an Engine is acceptable + here as well. By skipping the Engine creation + we don't even need a DBAPI to be available. + + Calls to context.execute() here emit the given string to the + script output. + + """ + url = config.get_main_option("sqlalchemy.url") + context.configure(url=url) + + with context.begin_transaction(): + context.run_migrations() + + +def run_migrations_online(): + """Run migrations in 'online' mode. + + In this scenario we need to create an Engine + and associate a connection with the context. + + """ + engine = engine_from_config(config.get_section(config.config_ini_section), + prefix='sqlalchemy.', + poolclass=pool.NullPool) + + connection = engine.connect() + context.configure(connection=connection, + target_metadata=target_metadata, + **current_app.extensions['migrate'].configure_args) + + try: + with context.begin_transaction(): + context.run_migrations() + finally: + connection.close() + +if context.is_offline_mode(): + run_migrations_offline() +else: + run_migrations_online() + diff --git a/neo1218/0023/web/migrations/script.py.mako b/neo1218/0023/web/migrations/script.py.mako new file mode 100644 index 00000000..95702017 --- /dev/null +++ b/neo1218/0023/web/migrations/script.py.mako @@ -0,0 +1,22 @@ +"""${message} + +Revision ID: ${up_revision} +Revises: ${down_revision} +Create Date: ${create_date} + +""" + +# revision identifiers, used by Alembic. +revision = ${repr(up_revision)} +down_revision = ${repr(down_revision)} + +from alembic import op +import sqlalchemy as sa +${imports if imports else ""} + +def upgrade(): + ${upgrades if upgrades else "pass"} + + +def downgrade(): + ${downgrades if downgrades else "pass"} diff --git a/neo1218/0023/web/migrations/versions/3277cb11e991_initial_migration.py b/neo1218/0023/web/migrations/versions/3277cb11e991_initial_migration.py new file mode 100644 index 00000000..e01abb43 --- /dev/null +++ b/neo1218/0023/web/migrations/versions/3277cb11e991_initial_migration.py @@ -0,0 +1,47 @@ +"""initial migration + +Revision ID: 3277cb11e991 +Revises: None +Create Date: 2015-05-10 08:39:17.826382 + +""" + +# revision identifiers, used by Alembic. +revision = '3277cb11e991' +down_revision = None + +from alembic import op +import sqlalchemy as sa + + +def upgrade(): + ### commands auto generated by Alembic - please adjust! ### + op.create_table('users', + sa.Column('id', sa.Integer(), nullable=False), + sa.Column('email', sa.String(length=64), nullable=True), + sa.Column('username', sa.String(length=64), nullable=True), + sa.Column('password_hash', sa.String(length=128), nullable=True), + sa.PrimaryKeyConstraint('id') + ) + op.create_index(op.f('ix_users_email'), 'users', ['email'], unique=True) + op.create_index(op.f('ix_users_username'), 'users', ['username'], unique=True) + op.create_table('posts', + sa.Column('id', sa.Integer(), nullable=False), + sa.Column('body', sa.Text(), nullable=True), + sa.Column('timestamp', sa.DateTime(), nullable=True), + sa.Column('author_id', sa.Integer(), nullable=True), + sa.ForeignKeyConstraint(['author_id'], ['users.id'], ), + sa.PrimaryKeyConstraint('id') + ) + op.create_index(op.f('ix_posts_timestamp'), 'posts', ['timestamp'], unique=False) + ### end Alembic commands ### + + +def downgrade(): + ### commands auto generated by Alembic - please adjust! ### + op.drop_index(op.f('ix_posts_timestamp'), table_name='posts') + op.drop_table('posts') + op.drop_index(op.f('ix_users_username'), table_name='users') + op.drop_index(op.f('ix_users_email'), table_name='users') + op.drop_table('users') + ### end Alembic commands ### diff --git a/neo1218/0023/web/requirements.txt b/neo1218/0023/web/requirements.txt new file mode 100644 index 00000000..39c98b4f --- /dev/null +++ b/neo1218/0023/web/requirements.txt @@ -0,0 +1,18 @@ +Flask==0.10.1 +Flask-Bootstrap==3.0.3.1 +Flask-Login==0.2.7 +Flask-Mail==0.9.0 +Flask-Migrate==1.1.0 +Flask-Moment==0.2.1 +Flask-SQLAlchemy==1.0 +Flask-Script==0.6.6 +Flask-WTF==0.9.4 +Jinja2==2.7.1 +Mako==0.9.1 +MarkupSafe==0.18 +SQLAlchemy==0.9.9 +WTForms==1.0.5 +Werkzeug==0.9.4 +alembic==0.6.2 +blinker==1.3 +itsdangerous==0.23 diff --git a/neo1218/0023/web/tests/__init__.py b/neo1218/0023/web/tests/__init__.py new file mode 100644 index 00000000..e69de29b diff --git a/neo1218/0023/web/tests/test_basics.py b/neo1218/0023/web/tests/test_basics.py new file mode 100644 index 00000000..0fdf4983 --- /dev/null +++ b/neo1218/0023/web/tests/test_basics.py @@ -0,0 +1,22 @@ +import unittest +from flask import current_app +from app import create_app, db + + +class BasicsTestCase(unittest.TestCase): + def setUp(self): + self.app = create_app('testing') + self.app_context = self.app.app_context() + self.app_context.push() + db.create_all() + + def tearDown(self): + db.session.remove() + db.drop_all() + self.app_context.pop() + + def test_app_exists(self): + self.assertFalse(current_app is None) + + def test_app_is_testing(self): + self.assertTrue(current_app.config['TESTING']) diff --git a/neo1218/0023/web/tests/test_user_model.py b/neo1218/0023/web/tests/test_user_model.py new file mode 100644 index 00000000..b705a3bc --- /dev/null +++ b/neo1218/0023/web/tests/test_user_model.py @@ -0,0 +1,35 @@ +import unittest +from app import create_app, db +from app.models import User + + +class UserModelTestCase(unittest.TestCase): + def setUp(self): + self.app = create_app('testing') + self.app_context = self.app.app_context() + self.app_context.push() + db.create_all() + + def tearDown(self): + db.session.remove() + db.drop_all() + self.app_context.pop() + + def test_password_setter(self): + u = User(password='cat') + self.assertTrue(u.password_hash is not None) + + def test_no_password_getter(self): + u = User(password='cat') + with self.assertRaises(AttributeError): + u.password + + def test_password_verification(self): + u = User(password='cat') + self.assertTrue(u.verify_password('cat')) + self.assertFalse(u.verify_password('dog')) + + def test_password_salts_are_random(self): + u = User(password='cat') + u2 = User(password='cat') + self.assertTrue(u.password_hash != u2.password_hash) diff --git a/neo1218/0023/web/wsgi.py b/neo1218/0023/web/wsgi.py new file mode 100644 index 00000000..69655517 --- /dev/null +++ b/neo1218/0023/web/wsgi.py @@ -0,0 +1,8 @@ +#!/usr/bin/env python +# encoding: utf-8 + +from manage import app + +if __name__ == "__main__": + app.run(host="121.43.230.104",port=5000) + diff --git a/partrita/0001/codes.txt b/partrita/0001/codes.txt new file mode 100644 index 00000000..53b52f4a --- /dev/null +++ b/partrita/0001/codes.txt @@ -0,0 +1,10 @@ +VTGwsgMjVt4rXtS +VcBNNj2wxpxzfIn +tRkSWNZvlKtGZ9t +GGfymamjpwD69rx +vMGIGYdAPwIG5zT +Mt60KsjdS6AdM4z +SsTkjAOskJCH1SJ +pG9w6OXJyNGNgu2 +er4a3ZxEg1XuX0g +lIe85Mgl7Dg9aIh diff --git a/partrita/0001/make_code.py b/partrita/0001/make_code.py new file mode 100644 index 00000000..f2b0a36e --- /dev/null +++ b/partrita/0001/make_code.py @@ -0,0 +1,25 @@ +# -*- coding: utf-8 -*- +""" +Created on Mon May 11 16:04:59 2015 + +@author: partrita +""" + +from random import Random + +def codeGenerator(number, codeLength = 15): + print '**** Code Generator ****' + codeFile = open('codes.txt', 'w') + if number <= 0: + return 'invalid number of codes' + else: + chars = 'abcdefghijklmnopgrstuvwxyzABCDEFGHIJKLMNOPGRSTUVWXYZ1234567890' + random = Random() + for j in range(1, number+1): + str = '' + for i in range(1, codeLength+1): + index = random.randint(1, len(chars)) + str = str + chars[index-1] + codeFile.write(str+'\n') + +print codeGenerator(10) \ No newline at end of file diff --git a/problem 0001/0001.py b/problem 0001/0001.py new file mode 100644 index 00000000..42848e97 --- /dev/null +++ b/problem 0001/0001.py @@ -0,0 +1,22 @@ +import string +import random +def coupon_creator(digit): + coupon='' + for word in range(digit): + coupon+=random.choice(string.ascii_uppercase + string.digits) + return coupon + +def two_hundred_coupons(): + data='' + count=1 + for count in range(200): + digit=12 + count+=1 + data+='coupon no.'+str(count)+' '+coupon_creator(digit)+'\n' + + return data + + +coupondata=open('coupondata.txt','w') +coupondata.write(two_hundred_coupons()) +coupondata.close() \ No newline at end of file diff --git a/problem 0001/coupondata.txt b/problem 0001/coupondata.txt new file mode 100644 index 00000000..68b17187 --- /dev/null +++ b/problem 0001/coupondata.txt @@ -0,0 +1,200 @@ +coupon no.1 FWJW0YIBITUL +coupon no.2 NQU7R8XJNBXG +coupon no.3 ZG9GKKMSB6HV +coupon no.4 O4XX21EKJX77 +coupon no.5 GUTI0CSN2C6X +coupon no.6 C4MS2L6ZUC3L +coupon no.7 6C9XNU5P9YNP +coupon no.8 TDWZHJMH79T7 +coupon no.9 NK42DPL2KO7S +coupon no.10 N9N53QOR49LF +coupon no.11 QFKY2FA9YHO6 +coupon no.12 MPISYC004GMD +coupon no.13 0JARTJT6INRB +coupon no.14 5YE7OWV5TPXZ +coupon no.15 T6Z42DZVZCV4 +coupon no.16 DOTG64M56IOZ +coupon no.17 63LOHIBWKQW0 +coupon no.18 QMW1WS74YPSF +coupon no.19 EDYA4BTEUEG8 +coupon no.20 3PP94R8DTXTH +coupon no.21 SWTYQIFG59ZJ +coupon no.22 5W66U5OE9EUL +coupon no.23 04K6XU9CYP1S +coupon no.24 380F1KRRJ952 +coupon no.25 Q7C3IBPCVGPG +coupon no.26 516U37YWS0TD +coupon no.27 PDZVA7NHPYIJ +coupon no.28 1H5ONS7OKN7Q +coupon no.29 CP447S7EIWCC +coupon no.30 CYVFITE5CHUJ +coupon no.31 XNYD11NWD3FN +coupon no.32 593GXVHNSR1I +coupon no.33 O4N12KSNXTQU +coupon no.34 3FSNMKHUA9GG +coupon no.35 5I6QC0FFEY55 +coupon no.36 T2H84ALIBJVS +coupon no.37 U0WAUXJDB0OG +coupon no.38 GUO20ACL1M18 +coupon no.39 2NDT0788JBT4 +coupon no.40 E9SFSETUOJZV +coupon no.41 1Y553JWA9DIT +coupon no.42 F1MQIGIVH1CV +coupon no.43 B9E303O9UW6O +coupon no.44 LTJI2OREX7FM +coupon no.45 L4YDRNS9UHFX +coupon no.46 T0L8MPN9U7BG +coupon no.47 0GK0Y1WR4RTE +coupon no.48 T08Y1R1F0FJA +coupon no.49 KU0ROH2G2DAZ +coupon no.50 AIXMX3R4P368 +coupon no.51 02A2IM6O36JY +coupon no.52 6T4855XEPR5J +coupon no.53 28P308KD20JK +coupon no.54 ZJVP7I1JYB3X +coupon no.55 EPY8ABOLUB1F +coupon no.56 UDBEUPSFVAY7 +coupon no.57 NOCBFKB5L68F +coupon no.58 TLK5PPPNTAYB +coupon no.59 O3OBACP3WDJV +coupon no.60 WKOCO2RMO3RB +coupon no.61 J69JSK7MPDYZ +coupon no.62 RGHO0FOCFT97 +coupon no.63 FO4XB61Y8WBV +coupon no.64 WGL60PE7P1OJ +coupon no.65 JDCAMB4K9EY9 +coupon no.66 AR5OPUT1WKSP +coupon no.67 RHDAXFBN9K1E +coupon no.68 05505M3PS7MJ +coupon no.69 JSI9TRQGLXMG +coupon no.70 OWCQSH53LLKM +coupon no.71 X4HCRNGD8B5J +coupon no.72 HP44PXN8W8B7 +coupon no.73 1H4IINT9ZDVG +coupon no.74 S63YHUKU5UPU +coupon no.75 OINDDAQYU3LQ +coupon no.76 B8RG2RL7JDEM +coupon no.77 LRH1KU8C42O6 +coupon no.78 ZKO3WO1K7ZN7 +coupon no.79 RA0LHH0ORS40 +coupon no.80 OVFUSWG36AJQ +coupon no.81 B2I23IWM0QDK +coupon no.82 2T66MPUSXLO8 +coupon no.83 UH8CDZE1A1FH +coupon no.84 0PF0QTBUNHXI +coupon no.85 RWHH6PJIM7AJ +coupon no.86 5G51MCB9GSLZ +coupon no.87 PWF1AXVE5BOK +coupon no.88 URJO6LTL1OL0 +coupon no.89 88PVJOLP8107 +coupon no.90 4QZSWWA6CXWM +coupon no.91 EM87EHTI6X8D +coupon no.92 KXF4P56RR6P1 +coupon no.93 BTNBZ2CHQR4V +coupon no.94 0W9S44Y8U16U +coupon no.95 0R4AZ9EB7D6X +coupon no.96 AZTKVO9LJJN9 +coupon no.97 6YTJ9N2TAQJB +coupon no.98 Y1IA11Y34I0D +coupon no.99 EWM4U6S4DBJN +coupon no.100 QD4AQ3A7STDP +coupon no.101 CHSNVU5ZW8GB +coupon no.102 1NHDYWU00Q3O +coupon no.103 QGTXZWO96PA9 +coupon no.104 49AP05QRNTRF +coupon no.105 9SXMO0QPWOCP +coupon no.106 I6A6GEJLNKHW +coupon no.107 F9FK75OXX340 +coupon no.108 WGFPSQWJSTQR +coupon no.109 YPF79O3X5NRT +coupon no.110 QN23EXDFKDW8 +coupon no.111 ZT4T54WRM7QK +coupon no.112 QA78PI358R74 +coupon no.113 S8UGJUXFZP6U +coupon no.114 WU6COWJW7DTM +coupon no.115 QPL1WSMCKLPD +coupon no.116 A98P5VQK74BP +coupon no.117 M6X08E3OURYN +coupon no.118 M8GF4JOFQZ0C +coupon no.119 TDTJV2I079TE +coupon no.120 LLMRA43NL2J9 +coupon no.121 2BYQY8EFL35L +coupon no.122 7B5ANII8ZHFW +coupon no.123 D20WEWW7OB21 +coupon no.124 Y8TWI7OF7H2L +coupon no.125 57CT9SZ03ZYB +coupon no.126 FHPAMN9EXI6P +coupon no.127 CPVFJQR6SI4K +coupon no.128 PXAUDBIGIQLJ +coupon no.129 SYACJYLSR19L +coupon no.130 ZX9586DVR42P +coupon no.131 FD3GK84USH9U +coupon no.132 L6MZWX28N5J3 +coupon no.133 R88G9MC9ZIW4 +coupon no.134 R25QCRFXWK7P +coupon no.135 811SMYNGDOJP +coupon no.136 CEYYUOVZU4WB +coupon no.137 GFFS1KRXBJRF +coupon no.138 V61XLSIBNJZ9 +coupon no.139 HHJRITKF8LA0 +coupon no.140 KMZNXQ4OXRYG +coupon no.141 AX5B3DODGMVG +coupon no.142 IDR4RZ0H9AN3 +coupon no.143 78HVUWSM2MFN +coupon no.144 HKETH9WRDEC8 +coupon no.145 NC9ESBZ5VILI +coupon no.146 4FLER6LSOLCH +coupon no.147 L0ZCC7SZHJ16 +coupon no.148 FPJN2MVKFRMD +coupon no.149 2FA6D4HBDGRC +coupon no.150 YLW7YHKA27CB +coupon no.151 R2AHCEVUZIWQ +coupon no.152 QWXGCIZSSMO5 +coupon no.153 A5M4DLS8JTY7 +coupon no.154 M8QYBQ50WLOU +coupon no.155 P2RNVDU6XH82 +coupon no.156 8N1BBAAEGBL8 +coupon no.157 2PJN5G0V4494 +coupon no.158 JS2QAIQ93R7S +coupon no.159 LRC9WWSREPBY +coupon no.160 ST3RYQ1NN5MG +coupon no.161 FQ0OCG793S9O +coupon no.162 JZ4K0DDF10F6 +coupon no.163 SDNL4Q58BDF1 +coupon no.164 PR7ZWO97BZ8R +coupon no.165 GWD0TPGLQG10 +coupon no.166 H627P3YBYJM2 +coupon no.167 2NBGKYA2GEEH +coupon no.168 R9NE8UVSZYQO +coupon no.169 6M6S808GQDJE +coupon no.170 1FJLZ72UJN9O +coupon no.171 QSWIVNAHY0ZV +coupon no.172 40U7D9KGNSNJ +coupon no.173 830BB34Z5UGD +coupon no.174 OED6Q8LMPB6V +coupon no.175 18VXH43MXZ5I +coupon no.176 TBXOPC35KTET +coupon no.177 NEKY3FDCXDWH +coupon no.178 722G2Y5IVHGF +coupon no.179 D0Y47HD6BQ9D +coupon no.180 OZI60AVBQ28I +coupon no.181 VXTAVAZWJ1G8 +coupon no.182 76M19IPC3C0T +coupon no.183 V791ZQMP9147 +coupon no.184 6BV4ED7Q8ZF6 +coupon no.185 ONUJDDRA78DI +coupon no.186 HRZOHHDTO9IG +coupon no.187 4K1ZX4X12G4F +coupon no.188 T6ZHZCCU85SF +coupon no.189 4WWQZF5ABACB +coupon no.190 ROXK6P3MNCT3 +coupon no.191 OWM6RQBOGF5S +coupon no.192 E2ESEJ9Y6HLJ +coupon no.193 DXJECVUTKZD5 +coupon no.194 2LMO21NCSBLG +coupon no.195 FCUQWL99QLMA +coupon no.196 HLJX67U1QQPB +coupon no.197 0CZ43NJZ9ZG3 +coupon no.198 01O9E5A0IFFP +coupon no.199 PCPUK158V1BS +coupon no.200 HJVY7ZB890D0 diff --git a/problem 0004/solution for problem 0004.py b/problem 0004/solution for problem 0004.py new file mode 100644 index 00000000..cdb4d9cb --- /dev/null +++ b/problem 0004/solution for problem 0004.py @@ -0,0 +1,9 @@ +def count(): + name = raw_input("Enter file:") + if len(name) < 1 : name = "test.txt" + handle = open(name) + count_words=list() + for line in handle: + count_words+=line.split() + return len(count_words) +print count() \ No newline at end of file diff --git a/python b/python new file mode 160000 index 00000000..4ae3b1cc --- /dev/null +++ b/python @@ -0,0 +1 @@ +Subproject commit 4ae3b1cc45266a9a769960696ead49087cc02cd3 diff --git a/rahulgsalecha/0001/calculator.py b/rahulgsalecha/0001/calculator.py new file mode 100644 index 00000000..1e7be212 --- /dev/null +++ b/rahulgsalecha/0001/calculator.py @@ -0,0 +1,38 @@ +#simple calculator + +#define functions + +def add(x,y): + return x + y + +def subtract(x,y): + return x-y + +def multiply(x,y): + return x*y + +def divide(x,y): + return x/y + +#take input from the user +print("Select Operation:") +print("1.Add") +print("2.Subtract") +print("3.Multiply") +print("4.Divide") + +choice = int(input("enter choice(1/2/3/4):")) + +num1 = int(input("Enter first number: ")) +num2 = int(input("Enter second number: ")) + +if choice == 1: + print(num1,"+",num2,"=", add(num1,num2)) +elif choice == 2: + print(num1,"-",num2,"=", subtract(num1,num2)) +elif choice == 3: + print(num1,"*",num2,"=", multiply(num1,num2)) +elif choice == 4: + print(num1,"/",num2,"=", divide(num1,num2)) +else: + print("Invalid input") diff --git a/rahulgsalecha/0001/result.txt b/rahulgsalecha/0001/result.txt new file mode 100644 index 00000000..f6def1a2 --- /dev/null +++ b/rahulgsalecha/0001/result.txt @@ -0,0 +1,96 @@ +TESTING$ python calculator.py +Select Operation: +1.Add +2.Subtract +3.Multiply +4.Divide +enter choice(1/2/3/4):1 +Enter first number: 3 +Enter second number: 2 +(3, '+', 2, '=', 5) +TESTING$ python calculator.py +Select Operation: +1.Add +2.Subtract +3.Multiply +4.Divide +enter choice(1/2/3/4):2 +Enter first number: 2 +Enter second number: 3 +(2, '-', 3, '=', -1) +TESTING$ python calculator.py +Select Operation: +1.Add +2.Subtract +3.Multiply +4.Divide +enter choice(1/2/3/4):3 +Enter first number: 5 +Enter second number: 6 +(5, '*', 6, '=', 30) +TESTING$ python calculator.py +Select Operation: +1.Add +2.Subtract +3.Multiply +4.Divide +enter choice(1/2/3/4):4 +Enter first number: 4 +Enter second number: 2 +(4, '/', 2, '=', 2) +TESTING$ python calculator.py +Select Operation: +1.Add +2.Subtract +3.Multiply +4.Divide +enter choice(1/2/3/4):1 +Enter first number: -1 +Enter second number: -1 +(-1, '+', -1, '=', -2) +TESTING$ python calculator.py +Select Operation: +1.Add +2.Subtract +3.Multiply +4.Divide +enter choice(1/2/3/4):2 +Enter first number: -1 +Enter second number: -1 +(-1, '-', -1, '=', 0) +TESTING$ python calculator.py +Select Operation: +1.Add +2.Subtract +3.Multiply +4.Divide +enter choice(1/2/3/4):3 +Enter first number: 0 +Enter second number: 0 +(0, '*', 0, '=', 0) +TESTING$ python calculator.py +Select Operation: +1.Add +2.Subtract +3.Multiply +4.Divide +enter choice(1/2/3/4):2 +Enter first number: 1 +Enter second number: 1 +(1, '-', 1, '=', 0) +TESTING$ python calculator.py +Select Operation: +1.Add +2.Subtract +3.Multiply +4.Divide +enter choice(1/2/3/4):4 +Enter first number: 0 +Enter second number: 0 +Traceback (most recent call last): + File "calculator.py", line 36, in + print(num1,"/",num2,"=", divide(num1,num2)) + File "calculator.py", line 15, in divide + return x/y +ZeroDivisionError: integer division or modulo by zero +TESTING$ diff --git a/razzl/0000/0000.py b/razzl/0000/0000.py new file mode 100644 index 00000000..35de70ff --- /dev/null +++ b/razzl/0000/0000.py @@ -0,0 +1,22 @@ +#!/usr/bin/env python + +''' +Draw a number on the image +''' + +try: + from PIL import Image + from PIL import ImageDraw + from PIL import ImageFont +except ImportError: + import Image,ImageFont,ImageDraw + +def draw_number(path = '/root/Desktop/1.jpg',num = 4): + im = Image.open(path)#open the picture + size = im.size#get the size of the picture + fontsize = size[0]/4 + draw = ImageDraw.Draw(im)#the ImageDraw.Draw will rerturn a object then you can draw it + font = ImageFont.truetype('/usr/share/fonts/dejavu/DejVuSans.ttf',fontsize)#define the font and size of the number + draw.text((3*fontsize,0),str(num),(255, 0, 0),font)#draw it + im.save('/root/Desktop/2.jpg')#save +draw_number() diff --git a/razzl/0001/0001.py b/razzl/0001/0001.py new file mode 100644 index 00000000..6337c64b --- /dev/null +++ b/razzl/0001/0001.py @@ -0,0 +1,17 @@ +#!/usr/bin/env python + +''' +It can generate the activation code +''' + +import random +#import string + +f = open('C:\Users\zzl\Desktop\2.txt','w') +for x in range(200): + words = [chr(a) for a in range(65,91)]+[chr(a) for a in range(97,122)]+[str(a) for a in range(0,11)] + # It is equal to string.ascii_letters + string.digits + slice = random.sample(words,10) + temp = str(words) + f.write(temp) +f.close() diff --git a/razzl/0002/0002.py b/razzl/0002/0002.py new file mode 100644 index 00000000..e5edfde2 --- /dev/null +++ b/razzl/0002/0002.py @@ -0,0 +1,39 @@ +#!/usr/bin/env python + +''' + It can save the contents of the file to the mysql database. +''' + +import os +import random +import MySQLdb +#import string + +f = open(os.getcwd()+'\\2','w') +for x in range(200): + words = [chr(a) for a in range(65,91)]+[chr(a) for a in range(97,122)]+[str(a) for a in range(0,11)] + # It is equal to string.ascii_letters + string.digits + slices = random.sample(words,10) + #temp = str(slices) + temp = "".join(slices)+'\n' + #print temp + f.write(temp) +f.close() + +f = open(os.getcwd()+'\\2','r') +words = f.readlines() +try: + conn = MySQLdb.connect(host = 'localhost', user = 'root', passwd = '******', port = 3306)#connet to your local database of mysql + + cur = conn.cursor() + + conn.select_db('python') + + count = cur.executemany('insert into test(name) values(%s)',words)#executemant need two parameters sql statement and list + + conn.commit()#commit the implementation results + cur.close()#close the cursor + conn.close()# close the connect +except MySQLdb.Error,e: + print "Mysql Error %d: %s" % (e.args[0], e.args[1]) + diff --git a/razzl/0004/0004.py b/razzl/0004/0004.py new file mode 100644 index 00000000..7df7cdba --- /dev/null +++ b/razzl/0004/0004.py @@ -0,0 +1,15 @@ +''' +It can caculate the words in the text file +''' + +import re +def calculate_words(path): + f = open(path,'r') + lines = f.readlines() + count = 0 + for line in lines: + count+=len(re.split('[,.! ?:]',line))#use the re module to split the txt file + return count-len(lines)#the txt file will inlcude the '\n' and '' so sub it + +words = calculate_words("C:/Users/razzl/Desktop/1.txt")#in python the '/' can be the path separator in all system +print words diff --git a/razzl/0005/0005.py b/razzl/0005/0005.py new file mode 100644 index 00000000..a79c5ea9 --- /dev/null +++ b/razzl/0005/0005.py @@ -0,0 +1,22 @@ +''' +It can resize the photos in a file +''' + +import os +from PIL import Image + +def resize_photo(source_dir,width,higth,destination_dir): + photos = os.listdir(source_dir) + for photo in photos: + photo_abspath = os.path.join(source_dir,photo)#if you use os.path.abspath,there may be some error + print photo_abspath + if(os.path.isfile(photo_abspath)):#os.path.isfile need a abspath + im = Image.open(photo_abspath) + #w,h = im.size + new_im = im.resize((width,higth))#note: the resize returns a resized copy of an image , so you need a new object to save it + destination_path = os.path.join(destination_dir,photo) + new_im.save(destination_path) + print destination_path +resize_photo('C:/Users/razzl/Desktop/1',800,800,'C:/Users/razzl/Desktop/2') + + diff --git a/renzongxian/0008/0008.py b/renzongxian/0008/0008.py index c3848093..35580ef0 100644 --- a/renzongxian/0008/0008.py +++ b/renzongxian/0008/0008.py @@ -16,7 +16,7 @@ def get_body(url): html_content = urllib.request.urlopen(url).read() r = re.compile('

(?:<.[^>]*>)?(.*?)(?:<.[^>]*>)?

') - result = r.findall(html_content.decode('GBK')) + result = r.findall(html_content.decode('GBK').encode('utf-8')) return result diff --git a/robot527/0011/word_filter.py b/robot527/0011/word_filter.py new file mode 100644 index 00000000..346195f3 --- /dev/null +++ b/robot527/0011/word_filter.py @@ -0,0 +1,54 @@ +#! /usr/bin/python +# -*- coding: utf-8 -*- +# word_filter.py +# author: robot527 +# created at 2016-4-22 + +''' +дıļ filtered_words.txtΪÿһһдʡ +ûдʱӡ Freedomӡ Human Rights +''' + +def get_words(words_file): + '''Get words from words_file''' + words = [] + text = open(words_file) + for each_line in text: + words.append(each_line.strip().decode('gb18030')) + #for w in words: + # print w, type(w) + text.close() + return words + + +def str_to_unicode(str1): + '''Convert str1 to unicode''' + if isinstance(str1, unicode): + return str1 + try: + string_uni = str1.decode("utf-8") + return string_uni + except UnicodeDecodeError as err: + print err + + +if __name__ == '__main__': + sensitive_words = get_words("filtered_words.txt") + running = True + while running: + print 'Please input a word, or press q for exit.' + try: + para = raw_input("-> ") + except EOFError: + print "If you want to quit, press Q key.\n" + continue + #uw = str_to_unicode(para) + #print uw, type(uw) + if str_to_unicode(para) in sensitive_words: + print "Freedom\n" + elif para is 'q': + para = raw_input("Do you really want to exit ([y]/n)?") + if para is not 'n': + running = False + else: + print "Human Rights\n" diff --git a/robot527/0012/filtered_words.txt b/robot527/0012/filtered_words.txt new file mode 100644 index 00000000..1b4f2244 --- /dev/null +++ b/robot527/0012/filtered_words.txt @@ -0,0 +1,11 @@ +北京 +程序员 +公务员 +领导 +牛比 +牛逼 +你娘 +你妈 +love +sex +jiangge diff --git a/robot527/0012/shield_sensitive_words.py b/robot527/0012/shield_sensitive_words.py new file mode 100644 index 00000000..689aeb3e --- /dev/null +++ b/robot527/0012/shield_sensitive_words.py @@ -0,0 +1,61 @@ +#! /usr/bin/python +# -*- coding: utf-8 -*- +# shield_sensitive_words.py +# author: robot527 +# created at 2016-4-26 + +''' +дıļ filtered_words.txtΪÿһһдʡ + +Ա +Ա +쵼 +ţ +ţ + + +love +sex +jiangge + +ûдʱǺ * 滻 +統û롸ǸóСɡ**ǸóС +''' + +def get_replace_str(word): + '''Generate word replace string for word''' + if word.isalnum(): + return '*' * len(word) + else: + return '*' * (len(word) / 3) + + +def get_words_dict(words_file): + '''Generate word replace dictionary from words_file''' + words = {} + text = open(words_file) + for each_line in text: + word = each_line.strip() + words[word] = get_replace_str(word) + text.close() + return words + + +if __name__ == '__main__': + sensitive_words = get_words_dict("filtered_words.txt") + running = True + while running: + print 'Please input a sentence, or press q for exit.' + try: + para = raw_input("-> ") + except EOFError: + print "If you want to quit, press Q key.\n" + continue + if para is 'q': + para = raw_input("Do you really want to exit ([y]/n)?") + if para is not 'n': + running = False + else: + for each in sensitive_words.keys(): + para = para.replace(each, sensitive_words[each]) + print para, '\n' diff --git a/rusia-rak/README.md b/rusia-rak/README.md new file mode 100644 index 00000000..dd7399f2 --- /dev/null +++ b/rusia-rak/README.md @@ -0,0 +1,5 @@ +# My Repository + +View my solutions through the url below. + +https://github.com/rusia-rak/My-Solutions-For-Show-Me-The-Code diff --git a/sandeepbvv11/0001/0001.py b/sandeepbvv11/0001/0001.py new file mode 100644 index 00000000..dc07ddaa --- /dev/null +++ b/sandeepbvv11/0001/0001.py @@ -0,0 +1,13 @@ +import uuid +import random +st= 'qwertyuiopasdfghjklzxcvbnm!@#$%^&*' +for i in range(0,200): + x=str(uuid.uuid4().fields[-1])[:10]+st + y='' + for j in range(0,10): + y+=random.choice(x) + print (y+"\n") + + + + diff --git a/sandeepbvv11/0001/IDs.txt b/sandeepbvv11/0001/IDs.txt new file mode 100644 index 00000000..072c81b2 --- /dev/null +++ b/sandeepbvv11/0001/IDs.txt @@ -0,0 +1,200 @@ +1633080030 +1575331450 +2576272470 +6025196078 +6749800715 +1809784356 +1103067567 +2317154466 +2387172619 +1311479942 +2177631153 +2370287260 +1162412523 +2518779639 +2243750316 +1938180132 +1591366150 +6188050497 +2740704135 +1600959530 +2659057887 +2345262636 +3739990209 +2002762930 +1917284190 +2693778613 +2709103722 +5489642575 +1876898180 +1238515989 +4165697613 +8088099212 +2724793887 +2049639056 +1104856673 +9166531473 +9282269858 +1448264591 +1386139747 +1065576292 +4204557152 +2512295415 +1050894477 +2524912544 +6692710623 +2616827417 +7458305235 +1044794447 +5098747466 +2797008072 +7724293396 +1111770796 +1461006658 +8989839708 +6913737732 +2187806510 +2698293925 +5016785151 +2603392454 +2409248575 +2154409098 +2334854535 +7242170605 +6087847902 +1868083093 +1558536908 +2686827506 +2053548015 +8415640657 +9152960105 +1633827298 +1584236906 +5785050546 +7180274223 +1765903205 +1337873601 +1780907326 +1822360329 +6926443396 +7399201643 +1928861800 +1134654553 +1320384102 +2233968778 +1455518823 +2517263032 +1169422273 +1716334763 +1161051209 +2015915750 +1172222839 +1986125462 +2691761365 +5616099885 +1339589794 +1698316598 +1646543965 +1149678559 +1694897607 +2748354798 +6778102246 +6210771279 +1843697405 +1157328700 +2311701369 +2354728221 +1676462923 +1406252700 +8164346992 +1597080590 +2087121727 +2581425250 +2360763824 +2719496354 +1996551439 +2307124705 +1590380101 +2033501264 +2074669740 +4330833648 +6876615313 +2197033238 +1706630780 +1492489223 +2756620317 +1879142971 +5121975454 +8565292030 +2725313491 +2916240089 +2784487922 +9672375423 +2156919306 +4857227306 +2140172516 +6028740948 +1783900706 +3855460378 +2743825061 +8344693520 +7227242087 +1276410280 +8338154889 +1404111534 +1466184954 +2368850546 +2688854049 +2481429282 +2632295224 +4492399381 +2231034178 +1575661525 +1557617235 +2673273294 +1186634339 +2078658558 +2557116528 +2147464885 +1493314057 +1016852420 +1231533029 +1363504328 +5751842538 +3130274956 +1762953006 +1919187578 +1613396255 +2140266457 +1252506424 +1718690455 +3714816841 +3729165890 +1709638350 +2553647887 +2422430080 +7186739897 +5175743127 +1939180977 +2387691619 +7026319394 +2126033877 +5044248245 +1304451862 +7791137498 +6527058140 +2529986191 +7005348341 +2561005708 +8121959066 +5634593318 +9063187949 +6972178424 +1903659460 +8855566396 +1085528406 +8036753003 +2057399339 +1136500130 +7911266804 +1021556078 diff --git a/sarikasama/0000/0000.py b/sarikasama/0000/0000.py new file mode 100644 index 00000000..c5c0815c --- /dev/null +++ b/sarikasama/0000/0000.py @@ -0,0 +1,24 @@ +#!/usr/bin/env python3 +#Add a number on my icon with the name "icon.png". +#My icon is a little ... big. +#Problem0000 + +from PIL import Image, ImageDraw, ImageFont + +def add_number(num): + im = Image.open("icon.png") + #make a image for showing the number + txt = Image.new('RGBA', im.size, (255,255,255,0)) + #use the font "arial.ttf" + fnt = ImageFont.truetype("arial.ttf",40) + #draw context + d = ImageDraw.Draw(txt) + #draw the number + d.text((im.size[0]-50 ,5), str(num), font=fnt, fill=(255,0,0,255)) + + out = Image.alpha_composite(im, txt) + out.show() + out.save("icon_"+str(num)+".png") + +if __name__ == '__main__': + add_number(42) diff --git a/sarikasama/0000/arial.ttf b/sarikasama/0000/arial.ttf new file mode 100644 index 00000000..7ff88f22 Binary files /dev/null and b/sarikasama/0000/arial.ttf differ diff --git a/sarikasama/0000/icon.png b/sarikasama/0000/icon.png new file mode 100644 index 00000000..b8e21672 Binary files /dev/null and b/sarikasama/0000/icon.png differ diff --git a/sarikasama/0000/icon_42.png b/sarikasama/0000/icon_42.png new file mode 100644 index 00000000..656e1adc Binary files /dev/null and b/sarikasama/0000/icon_42.png differ diff --git a/sarikasama/0001/0001.py b/sarikasama/0001/0001.py new file mode 100644 index 00000000..51cbb023 --- /dev/null +++ b/sarikasama/0001/0001.py @@ -0,0 +1,17 @@ +#!/usr/bin/env python3 +#generate 200 activation codes for my apple store app + +import random, string + +def gene_activation_code(count, length): + #make sure codes are diffrent + res = set() + while len(res) < count: + res.add(''.join(random.choice(string.ascii_uppercase + string.digits) for _ in range(length))) + return res + +if __name__ == "__main__": + res = gene_activation_code(200, 8) + f = open("codes","w") + f.write("\n".join(res)) + f.close() diff --git a/sarikasama/0001/codes b/sarikasama/0001/codes new file mode 100644 index 00000000..88130bcf --- /dev/null +++ b/sarikasama/0001/codes @@ -0,0 +1,200 @@ +9HM28I2V +YUTUSWLX +KO910ZXR +1XQ7OMTH +R8B8XWT3 +CAZDMATI +HNHAU3QA +VR2A5O8L +1A2TG34C +X3JT0T0B +H4LSILG3 +BCICBNNJ +LUFUT2S0 +4H51EV7M +WMHE0LX1 +LBO6B5U7 +EJG3J6ZZ +YQCQV5IS +3SEL07K3 +N288TJEL +VFCC0K2B +P8J9ZG5N +TDY65TGQ +JGR14QYY +012QG5J7 +JJD09E6O +1V6QXSND +MITES6G1 +V3C09ACE +2I84H8D9 +ZR9VA4OR +0J8VTCFY +XCBB9HWF +GS1NL6UB +70GO84CW +T1V48W99 +H4L9PCSG +0XSXAQT0 +D7J98ZSY +IKB10A5S +VQGZ5L4C +WJU2IMH8 +0XTNP65W +XQ671726 +LCIMNOH4 +R36ZXNGT +NU04BJOR +P2IJVBEP +JT1SCFZC +69Y6VQ7A +V5D5G6X2 +9GCKGK6M +UB5G5OHX +BGA0KKP6 +6V5TSJ58 +570VS9I6 +E03UJCOB +J2UCMXGT +8J7XBKU4 +MIJJDS35 +TCJFR4OU +AT1M8RXF +6G7PZVXU +9601SLTJ +G585YO17 +FOO71FXH +N4TM1W45 +D0UZGV1C +3X44O8AC +A89NHFE7 +9PRH0BYM +JFC3X18B +HXBZY6DL +2S3LZAPT +HX572VEB +WX0W7R99 +VKYBQBRI +ZDU36TBC +4L4EU1Y5 +TEBGN81Y +BDJFCK9I +SXA2D5EZ +FCG7VJN0 +MWIEFAM2 +E8TO1EY5 +1JRU6F31 +7N70U7N7 +CSIWDBUK +VQ8KR73I +ISHABRX5 +2TXRGDJ8 +Z90BQBSG +WSBJ4X3L +34EKGUR8 +A63CJ0F0 +4QJ9TB49 +PTVLGUF3 +A9B0PY0K +ZVP29VCK +K3H9331J +21HG6P11 +W6GZAVVD +I5HGBM6P +8RTCLY8R +5A860OIH +VLN2ZB37 +7DRYVPHU +FWI0HDAD +6P9RGQ8Z +7F9Q10FR +7HNH3EWP +PFHK18Z6 +5VS9PKLC +AZMBWSKW +XA30TWRJ +V6HI00G4 +A385GB8L +1UFF62RI +3TL6B4D4 +JYWHW6EY +JZ7X5R31 +FG51SGUY +Z7YTXLGF +J3AVBX3P +FNV19XYR +M3I2Q6EV +YY35QIOS +J2BMJVP3 +XW9HM2HB +1873CQQ8 +KGL61SL7 +TU41J8F4 +U1UCSYE5 +4L45MMQ9 +MFQLY7CB +MKFH50ZZ +LQ44DAW9 +8599GTIB +IGCT34SA +Q39B1TOJ +LANF45HH +72PJTWPK +F0XPL1ZO +5U7KOGZ9 +6M1MMXZ1 +HVZQD6RB +H2D50E2W +WJEXAK1L +I4CBC1W5 +X9XRXBS3 +DBNDT60B +6C6QJW0V +H8J8ZW8D +64MUB2X0 +8R44E4P9 +R83AV775 +UBRSJBPF +JN36LDJW +3C2EEMIQ +HRE1S0SK +SH8QH70P +3BI5Q1ZF +1VAQQXA0 +QGY6Y7G6 +1QQ9FLV7 +AP1SNJP2 +G68VA57Y +N6UHT54O +7Q9BB5JL +B4PIP9CJ +BAS3O1FH +L6Q6YVSH +APRT16IN +K4205WGU +R00E9H6L +6MW091Y5 +ERCE510B +U8XKOESQ +1YAXZEFB +KESINTFI +03DUWJYK +VRFUU0ZR +F5E4B6FX +XSEBU1JQ +3E692DCL +SF5A49NX +7P73NY4S +FAI8YPYC +TDA6FHLT +1NIX4S8W +R549CDKZ +CHK907PO +5S8BU9CN +XJIK45B5 +PK1PKL3K +UDU54DY7 +G863ES4G +GNW10XUX +FEBRWV5F +88I6TN3R \ No newline at end of file diff --git a/sarikasama/0004/0004.py b/sarikasama/0004/0004.py new file mode 100644 index 00000000..864fbfd2 --- /dev/null +++ b/sarikasama/0004/0004.py @@ -0,0 +1,23 @@ +#!/usr/bin/env python3 +#count words in a textfile + +from pprint import pprint +import re + +def main(): + res = {} + with open('test','r') as f: + content = f.read() + tmp = re.split(r"[^a-zA-Z]",content) + for w in tmp: + if not w: + continue + w = w.lower() + if w not in res: + res[w] = 1 + else: + res[w] += 1 + pprint(res) + +if __name__ == "__main__": + main() diff --git a/sarikasama/0004/output b/sarikasama/0004/output new file mode 100644 index 00000000..2bd14c75 --- /dev/null +++ b/sarikasama/0004/output @@ -0,0 +1,107 @@ +{'a': 5, + 'about': 1, + 'age': 1, + 'all': 1, + 'always': 2, + 'an': 1, + 'and': 1, + 'arms': 1, + 'as': 2, + 'at': 4, + 'been': 1, + 'before': 1, + 'born': 1, + 'but': 1, + 'by': 1, + 'can': 1, + 'child': 1, + 'count': 1, + 'did': 3, + 'dolly': 1, + 'dolores': 1, + 'dotted': 1, + 'down': 1, + 'envied': 1, + 'exhibit': 1, + 'fact': 1, + 'fancy': 1, + 'feet': 1, + 'fire': 1, + 'for': 1, + 'four': 1, + 'gentlemen': 1, + 'girl': 1, + 'had': 1, + 'have': 2, + 'i': 1, + 'in': 6, + 'indeed': 1, + 'initial': 1, + 'is': 1, + 'jury': 1, + 'ladies': 1, + 'lee': 2, + 'life': 1, + 'light': 1, + 'line': 1, + 'lo': 4, + 'loins': 1, + 'lola': 1, + 'lolita': 4, + 'look': 1, + 'loved': 1, + 'many': 1, + 'might': 1, + 'misinformed': 1, + 'morning': 1, + 'murderer': 1, + 'my': 6, + 'no': 1, + 'noble': 1, + 'not': 1, + 'number': 1, + 'of': 7, + 'oh': 1, + 'on': 3, + 'one': 3, + 'palate': 1, + 'plain': 1, + 'point': 1, + 'precursor': 1, + 'princedom': 1, + 'prose': 1, + 'school': 1, + 'sea': 1, + 'seraphs': 2, + 'she': 8, + 'simple': 1, + 'sin': 1, + 'slacks': 1, + 'sock': 1, + 'soul': 1, + 'standing': 1, + 'steps': 1, + 'style': 1, + 'summer': 2, + 'ta': 2, + 'taking': 1, + 'tangle': 1, + 'tap': 1, + 'teeth': 1, + 'ten': 1, + 'that': 1, + 'the': 10, + 'there': 1, + 'this': 1, + 'thorns': 1, + 'three': 2, + 'tip': 1, + 'to': 1, + 'tongue': 1, + 'trip': 1, + 'was': 7, + 'what': 1, + 'when': 1, + 'winged': 1, + 'years': 1, + 'you': 1} diff --git a/sarikasama/0004/test b/sarikasama/0004/test new file mode 100644 index 00000000..c18efc11 --- /dev/null +++ b/sarikasama/0004/test @@ -0,0 +1 @@ +Lolita, light of my life, fire of my loins. My sin, my soul. Lo-lee-ta: the tip of the tongue taking a trip of three steps down the palate to tap, at three, on the teeth. Lo. Lee. Ta. She was Lo, plain Lo, in the morning, standing four feet ten in one sock. She was Lola in slacks. She was Dolly at school. She was Dolores on the dotted line. But in my arms she was always Lolita. Did she have a precursor? She did, indeed she did. In point of fact, there might have been no Lolita at all had I not loved, one summer, an initial girl-child. In a princedom by the sea. Oh when? About as many years before Lolita was born as my age was that summer. You can always count on a murderer for a fancy prose style. Ladies and gentlemen of the jury, exhibit number one is what the seraphs, the misinformed, simple, noble-winged seraphs, envied. Look at this tangle of thorns. \ No newline at end of file diff --git a/sarikasama/0005/0005.py b/sarikasama/0005/0005.py new file mode 100644 index 00000000..8d275531 --- /dev/null +++ b/sarikasama/0005/0005.py @@ -0,0 +1,18 @@ +#!/usr/bin/env python3 +#change the resolution of pics in dir 'test' to at most 1136*640 for iphone5 +from PIL import Image +import os + +def main(): + os.chdir('test') + for root,dirs,files in os.walk(os.getcwd()): + for f in files: + im = Image.open(f) + if im.size[0] > 1136: + im.resize([1136,im.size[1]]) + if im.size[1] > 640: + im.resize([im.size[0],640]) + im.save('test_'+im.filename) + +if __name__=='__main__': + main() diff --git a/sarikasama/0006/0006.py b/sarikasama/0006/0006.py new file mode 100644 index 00000000..66823951 --- /dev/null +++ b/sarikasama/0006/0006.py @@ -0,0 +1,40 @@ +#!/usr/bin/env python3 +#get the most important word in the text + +import os, re +from pprint import pprint + +def most_important_word(f): + #get the count of words in the text + res = {} + content = f.read() + tmp = re.split(r"[^a-zA-Z]",content) + for w in tmp: + if not w: + continue + w = w.lower() + if w not in res: + res[w] = 1 + else: + res[w] += 1 + + #get the word of most importance + res['']=0 + max = '' + for i in res: + if res[i] > res[max]: + max = i + return max + +def main(): + res = {} + os.chdir('test') + for root,dirs,files in os.walk(os.getcwd()): + for file in files: + with open(file,'r') as f: + res[f.name]=most_important_word(f) + return res + +if __name__ == "__main__": + res = main() + pprint(res) diff --git a/sarikasama/0007/0007.py b/sarikasama/0007/0007.py new file mode 100644 index 00000000..ba8c417a --- /dev/null +++ b/sarikasama/0007/0007.py @@ -0,0 +1,35 @@ +#!/usr/bin/env python3 +#count lines of code in directory 'test' + +import os + +def count_lines(f): + #get the count of lines in the code + total = note = empty_row = 0 + line = f.readline() + while line != '': + if line[0] == '#': + note += 1 + total += 1 + elif line == '\n': + empty_row += 1 + total += 1 + else: + total += 1 + line = f.readline() + return total, note, empty_row + +def main(): + res = {} + os.chdir('test') + for root,dirs,files in os.walk(os.getcwd()): + for file in files: + with open(file,'r') as f: + res[f.name]=count_lines(f) + return res + +if __name__=="__main__": + res = main() + for i in res: + print(i+"\ntotal:"+str(res[i][0])+"\nnote:"+str(res[i][1])+"\nempty_line:"+str(res[i][2])) + print("\n") diff --git a/sarikasama/0008/0008.py b/sarikasama/0008/0008.py new file mode 100644 index 00000000..1f50c6dc --- /dev/null +++ b/sarikasama/0008/0008.py @@ -0,0 +1,26 @@ +#!/usr/bin/env pyhton3 +#get the text in a html file + +import re, urllib.request + +def get_text(url): + content = url.read() + try: + content = content.decode('utf-8') + except: + content = content.decode('gbk') + + content = re.sub(r'', '', content, flags = re.DOTALL) + content = re.sub(r'', '', content, flags = re.DOTALL) + content = re.sub(r'', '', content, flags = re.DOTALL) + content = re.sub(r'<[^>]*>', '', content) + content = re.sub(r'\n', '', content) + + print(content) + +def main(): + with urllib.request.urlopen('http://thwiki.cc/') as url: + get_text(url) + +if __name__ == '__main__': + main() diff --git a/sarikasama/0009/0009.py b/sarikasama/0009/0009.py new file mode 100644 index 00000000..454f1460 --- /dev/null +++ b/sarikasama/0009/0009.py @@ -0,0 +1,18 @@ +#!/usr/bin/env pyhton3 +#get the link in a html file + +import re, urllib.request +from lxml.html import parse + +def get_link(url): + dom = parse(url).getroot() + links = dom.xpath('//a') + for link in links: + link = link + try: + print(link.attrib['href']) + except: + pass + +if __name__ == '__main__': + get_link('http://thwiki.cc/') diff --git a/sarikasama/0010/0010.py b/sarikasama/0010/0010.py new file mode 100644 index 00000000..01125d7b --- /dev/null +++ b/sarikasama/0010/0010.py @@ -0,0 +1,29 @@ +#!/usr/bin/env python3 +#generate random verification codes in letters + +import random, string +from PIL import Image, ImageDraw, ImageFont, ImageFilter + +def gene_verification_code_pic(): + #initialize + im = Image.new('RGB', (200, 50), (255, 255, 255)) + font = ImageFont.truetype('arial.ttf', 30) + draw = ImageDraw.Draw(im) + + #init background with light color + for i in range(200): + for j in range(50): + draw.point((i, j), fill=(random.randint(128,255),random.randint(128,255),random.randint(128,255))) + + #init letters with deep color + for t in range(4): + draw.text((50*t+10, 10), random.choice(string.ascii_letters), font=font, fill=(random.randint(0,127), random.randint(0,127), random.randint(0,127))) + + #make the pic blurred + im = im.filter(ImageFilter.BLUR) + return im + +if __name__ == '__main__': + im = gene_verification_code_pic() + im.show() + im.save('res.jpg') diff --git a/sarikasama/0010/arial.ttf b/sarikasama/0010/arial.ttf new file mode 100644 index 00000000..7ff88f22 Binary files /dev/null and b/sarikasama/0010/arial.ttf differ diff --git a/sarikasama/0010/res.jpg b/sarikasama/0010/res.jpg new file mode 100644 index 00000000..e079b88c Binary files /dev/null and b/sarikasama/0010/res.jpg differ diff --git a/sarikasama/0011/0011.py b/sarikasama/0011/0011.py new file mode 100644 index 00000000..c105c831 --- /dev/null +++ b/sarikasama/0011/0011.py @@ -0,0 +1,19 @@ +#!/usr/bin/env python3 +#filter sensitive words in user's input + +def filter_sensitive_words(input_word): + s_words = [] + with open('filtered_words','r') as f: + line = f.readline() + while line != '': + s_words.append(line.strip()) + line = f.readline() + if input_word in s_words: + print("Freedom") + else: + print("Human Rights") + +if __name__ == '__main__': + while True: + input_word = input('--> ') + filter_sensitive_words(input_word) diff --git a/sarikasama/0011/filtered_words b/sarikasama/0011/filtered_words new file mode 100644 index 00000000..f0da7ccc --- /dev/null +++ b/sarikasama/0011/filtered_words @@ -0,0 +1,11 @@ +北京 +程序员 +公务员 +领导 +牛比 +牛逼 +你娘 +你妈 +love +sex + jiangge diff --git a/sarikasama/0012/0012.py b/sarikasama/0012/0012.py new file mode 100644 index 00000000..df193d81 --- /dev/null +++ b/sarikasama/0012/0012.py @@ -0,0 +1,19 @@ +#!/usr/bin/env python3 +#filter sensitive words in user's input + +def replace_sensitive_words(input_word): + s_words = [] + with open('filtered_words','r') as f: + line = f.readline() + while line != '': + s_words.append(line.strip()) + line = f.readline() + for word in s_words: + if word in input_word: + input_word = input_word.replace(word, "**") + print(input_word) + +if __name__ == '__main__': + while True: + input_word = input('--> ') + replace_sensitive_words(input_word) diff --git a/sarikasama/0012/filtered_words b/sarikasama/0012/filtered_words new file mode 100644 index 00000000..f0da7ccc --- /dev/null +++ b/sarikasama/0012/filtered_words @@ -0,0 +1,11 @@ +北京 +程序员 +公务员 +领导 +牛比 +牛逼 +你娘 +你妈 +love +sex + jiangge diff --git a/sarikasama/0013/0013.py b/sarikasama/0013/0013.py new file mode 100644 index 00000000..76ee61a1 --- /dev/null +++ b/sarikasama/0013/0013.py @@ -0,0 +1,26 @@ +#!/usr/bin/env python3 +#get all pic in a url + +from urllib.request import urlopen +from bs4 import BeautifulSoup + +def img_crawler(url): + content = url.read() + bs_object = BeautifulSoup(content) + bs_imgs = bs_object.find_all('img', pic_type='0') + + for img in bs_imgs: + img_url = img['src'] + try: + img_content = urlopen(img_url).read() + except: + pass + print("Downloading... "+img_url) + img_f = open(img_url.split('/')[-1], 'wb') + img_f.write(img_content) + img_f.close() + print("Complete!") + +if __name__ == '__main__': + url = urlopen('http://tieba.baidu.com/p/2166231880') + img_crawler(url) diff --git a/sarikasama/0014/0014.py b/sarikasama/0014/0014.py new file mode 100644 index 00000000..6d082f91 --- /dev/null +++ b/sarikasama/0014/0014.py @@ -0,0 +1,20 @@ +#!/usr/bin/env python3 +#from json to xlsx + +import xlsxwriter, json + +def json2xls(): + wb = xlsxwriter.Workbook('student.xls') + ws = wb.add_worksheet("student") + + with open('./student') as f: + data = json.load(f) + for i in range(len(data)): + ws.write(i, 0, i+1) + json_data = data[str(i+1)] + for j in range(len(json_data)): + ws.write(i, j+1, json_data[j]) + wb.close() + +if __name__=='__main__': + json2xls() diff --git a/sarikasama/0014/student b/sarikasama/0014/student new file mode 100644 index 00000000..1c4ffe6d --- /dev/null +++ b/sarikasama/0014/student @@ -0,0 +1,5 @@ +{ + "1":["张三",150,120,100], + "2":["李四",90,99,95], + "3":["王五",60,66,68] +} diff --git a/sarikasama/0014/student.xls b/sarikasama/0014/student.xls new file mode 100644 index 00000000..8575f90c Binary files /dev/null and b/sarikasama/0014/student.xls differ diff --git a/sarikasama/0015/0015.py b/sarikasama/0015/0015.py new file mode 100644 index 00000000..64371333 --- /dev/null +++ b/sarikasama/0015/0015.py @@ -0,0 +1,18 @@ +#!/usr/bin/env python3 +#from json to xlsx + +import xlsxwriter, json + +def json2xls(): + wb = xlsxwriter.Workbook('city.xls') + ws = wb.add_worksheet("city") + + with open('./city') as f: + data = json.load(f) + for i in range(len(data)): + ws.write(i, 0, i+1) + ws.write(i, 1, data[str(i+1)]) + wb.close() + +if __name__=='__main__': + json2xls() diff --git a/sarikasama/0015/city b/sarikasama/0015/city new file mode 100644 index 00000000..b5a6874d --- /dev/null +++ b/sarikasama/0015/city @@ -0,0 +1,5 @@ +{ + "1" : "上海", + "2" : "北京", + "3" : "成都" +} diff --git a/sarikasama/0015/city.xls b/sarikasama/0015/city.xls new file mode 100644 index 00000000..c4d1e10b Binary files /dev/null and b/sarikasama/0015/city.xls differ diff --git a/sarikasama/0016/0016.py b/sarikasama/0016/0016.py new file mode 100644 index 00000000..269e8997 --- /dev/null +++ b/sarikasama/0016/0016.py @@ -0,0 +1,18 @@ +#!/usr/bin/env python3 +#from json to xlsx + +import xlsxwriter, json + +def json2xls(): + wb = xlsxwriter.Workbook('numbers.xls') + ws = wb.add_worksheet("numbers") + + with open('./numbers') as f: + data = json.load(f) + for i in range(len(data)): + for j in range(len(data[i])): + ws.write(i, j, data[i][j]) + wb.close() + +if __name__=='__main__': + json2xls() diff --git a/sarikasama/0016/numbers b/sarikasama/0016/numbers new file mode 100644 index 00000000..dbe6d92f --- /dev/null +++ b/sarikasama/0016/numbers @@ -0,0 +1,5 @@ +[ + [1, 82, 65535], + [20, 90, 13], + [26, 809, 1024] +] diff --git a/sarikasama/0016/numbers.xls b/sarikasama/0016/numbers.xls new file mode 100644 index 00000000..e5ea32d8 Binary files /dev/null and b/sarikasama/0016/numbers.xls differ diff --git a/sarikasama/0017/0017.py b/sarikasama/0017/0017.py new file mode 100644 index 00000000..d42a7595 --- /dev/null +++ b/sarikasama/0017/0017.py @@ -0,0 +1,26 @@ +#!/usr/bin/env python3 +#convert from xls to xml + +import xlrd, json +from lxml import etree +from collections import OrderedDict + +def xls2xml(xls_name): + with xlrd.open_workbook(xls_name) as wb: + ws = wb.sheet_by_index(0) + table = OrderedDict() + for i in range(ws.nrows): + key = int(ws.row_values(i)[0]) + value = str(ws.row_values(i)[1:]) + table[key] = value + + with open("student.xml", 'w') as f: + root = etree.Element("root") + e_root = etree.ElementTree(root) + e_students = etree.SubElement(root, 'students') + e_students.text = '\n'+str(json.dumps(table, indent=4, ensure_ascii=False))+'\n' + e_students.append(etree.Comment('\n 学生信息表\n "id" : [名字,数学,语文,英语]\n')) + f.write(''+etree.tounicode(e_root.getroot())) + +if __name__=="__main__": + xls2xml('student.xls') diff --git a/sarikasama/0017/student.xls b/sarikasama/0017/student.xls new file mode 100644 index 00000000..8575f90c Binary files /dev/null and b/sarikasama/0017/student.xls differ diff --git a/sarikasama/0017/student.xml b/sarikasama/0017/student.xml new file mode 100644 index 00000000..bb68d95c --- /dev/null +++ b/sarikasama/0017/student.xml @@ -0,0 +1,10 @@ + +{ + "1": "['张三', 150.0, 120.0, 100.0]", + "2": "['李四', 90.0, 99.0, 95.0]", + "3": "['王五', 60.0, 66.0, 68.0]" +} + diff --git a/sarikasama/0018/0018.py b/sarikasama/0018/0018.py new file mode 100644 index 00000000..277f1ba9 --- /dev/null +++ b/sarikasama/0018/0018.py @@ -0,0 +1,26 @@ +#!/usr/bin/env python3 +#convert from xls to xml + +import xlrd, json +from lxml import etree +from collections import OrderedDict + +def xls2xml(xls_name): + with xlrd.open_workbook(xls_name) as wb: + ws = wb.sheet_by_index(0) + table = OrderedDict() + for i in range(ws.nrows): + key = int(ws.row_values(i)[0]) + value = ws.row_values(i)[1] + table[key] = value + + with open("city.xml", 'w') as f: + root = etree.Element("root") + e_root = etree.ElementTree(root) + e_citys = etree.SubElement(root, 'citys') + e_citys.text = '\n'+str(json.dumps(table, indent=4, ensure_ascii=False))+'\n' + e_citys.append(etree.Comment('\n 城市信息\n')) + f.write(''+etree.tounicode(e_root.getroot())) + +if __name__=="__main__": + xls2xml('city.xls') diff --git a/sarikasama/0018/city.xls b/sarikasama/0018/city.xls new file mode 100644 index 00000000..c4d1e10b Binary files /dev/null and b/sarikasama/0018/city.xls differ diff --git a/sarikasama/0018/city.xml b/sarikasama/0018/city.xml new file mode 100644 index 00000000..0db0e9cb --- /dev/null +++ b/sarikasama/0018/city.xml @@ -0,0 +1,9 @@ + +{ + "1": "上海", + "2": "北京", + "3": "成都" +} + diff --git a/sarikasama/0019/0019.py b/sarikasama/0019/0019.py new file mode 100644 index 00000000..1f10af93 --- /dev/null +++ b/sarikasama/0019/0019.py @@ -0,0 +1,23 @@ +#!/usr/bin/env python3 +#convert from xls to xml + +import xlrd, json +from lxml import etree + +def xls2xml(xls_name): + with xlrd.open_workbook(xls_name) as wb: + ws = wb.sheet_by_index(0) + table = [] + for i in range(ws.nrows): + table.append(ws.row_values(i)) + + with open("numbers.xml", 'w') as f: + root = etree.Element("root") + e_root = etree.ElementTree(root) + e_numbers = etree.SubElement(root, 'numbers') + e_numbers.text = '\n'+str(json.dumps(table, indent=4))+'\n' + e_numbers.append(etree.Comment('\n 数字信息\n')) + f.write(''+etree.tounicode(e_root.getroot())) + +if __name__=="__main__": + xls2xml('numbers.xls') diff --git a/sarikasama/0019/numbers.xls b/sarikasama/0019/numbers.xls new file mode 100644 index 00000000..e5ea32d8 Binary files /dev/null and b/sarikasama/0019/numbers.xls differ diff --git a/sarikasama/0019/numbers.xml b/sarikasama/0019/numbers.xml new file mode 100644 index 00000000..951bb1d1 --- /dev/null +++ b/sarikasama/0019/numbers.xml @@ -0,0 +1,21 @@ + +[ + [ + 1.0, + 82.0, + 65535.0 + ], + [ + 20.0, + 90.0, + 13.0 + ], + [ + 26.0, + 809.0, + 1024.0 + ] +] + diff --git a/sarikasama/0021/0021.py b/sarikasama/0021/0021.py new file mode 100644 index 00000000..648a830f --- /dev/null +++ b/sarikasama/0021/0021.py @@ -0,0 +1,18 @@ +#!/usr/bin/env python3 + +import hmac, hashlib, os + +def encrypt_passwd(password, salt=None): + if salt is None: + salt = str(os.urandom(8)).encode('utf-8') + if isinstance(password, str): + password = password.encode('utf-8') + + result = password + for i in range(10): + result = hmac.HMAC(result, salt, hashlib.sha256).digest() + return salt+result + +if __name__=="__main__": + e_passwd = encrypt_passwd(b'hello') + print(e_passwd) diff --git a/sarikasama/0022/0022.py b/sarikasama/0022/0022.py new file mode 100644 index 00000000..269a1af9 --- /dev/null +++ b/sarikasama/0022/0022.py @@ -0,0 +1,32 @@ +#!/usr/bin/env python3 +#change the resolution of pics in dir 'test' to at most 1136*640 for iphone5, 1334*750 for iphone6, or 1920*1080 for iphone6 Plus. +from PIL import Image +import os + +def main(): + os.chdir('test') + flag = input("Which shen do you use?\n1:iphone5\n2:iphone6\n3:iphone Plus") + for root,dirs,files in os.walk(os.getcwd()): + for f in files: + im = Image.open(f) + if flag == 1: + if im.size[0] > 1136: + im.resize([1136,im.size[1]]) + if im.size[1] > 640: + im.resize([im.size[0],640]) + elif flag == 2: + if im.size[0] > 1334: + im.resize([1136,im.size[1]]) + if im.size[1] > 750: + im.resize([im.size[0],750]) + elif flag == 3: + if im.size[0] > 1920: + im.resize([1136,im.size[1]]) + if im.size[1] > 1080: + im.resize([im.size[0],1080]) + else: + print("Input fault.") + im.save('test_'+im.filename) + +if __name__=='__main__': + main() diff --git a/sarikasama/README.md b/sarikasama/README.md new file mode 100644 index 00000000..3dc0eb68 --- /dev/null +++ b/sarikasama/README.md @@ -0,0 +1,2 @@ +# My version of show-me-the-code +No environment for debuging 0002, 0003 and 0020, so i ignored them diff --git a/sophie2805/0001/Practice_0001.py b/sophie2805/0001/Practice_0001.py new file mode 100644 index 00000000..65f63215 --- /dev/null +++ b/sophie2805/0001/Practice_0001.py @@ -0,0 +1,27 @@ +#! /usr/bin/env python +#! -*- coding:utf-8 -*- + +import random, string +__author__ = 'Sophie' + +def randomSequence(r,l): + s = string.letters + string.digits + '@#$%&*' + random_seq = [] + + # Method_1 + #for i in range(r): + # random_seq.append(''.join(random.sample(s,l))) + #return random_seq + + # Method_2 + sl = list(s) + print sl + for i in range(r): + random.shuffle(sl) + random_seq.append(''.join(sl[:l])) + return random_seq + +if __name__ == '__main__': + result = randomSequence(200,8) + for i in range(len(result)): + print result[i] \ No newline at end of file diff --git a/stingroc/0001/0001.py b/stingroc/0001/0001.py new file mode 100644 index 00000000..36e8c879 --- /dev/null +++ b/stingroc/0001/0001.py @@ -0,0 +1,28 @@ +import random + +if __name__ == "__main__": + NUM_OF_TICKET = 20 + LENGTH_OF_TICKET = 10 + + char_lst = [] + + def get_lst(lst, c1, c2): + char_lst = lst[0] + for i in range(ord(c1), ord(c2) + 1): + char_lst.append(chr(i)) + + get_lst([char_lst], '0', '9') + get_lst([char_lst], 'a', 'z') + get_lst([char_lst], 'A', 'Z') + + def gen_ticket(): + single_ticket_lst = [char_lst[random.randint(0, len(char_lst) - 1)] + for i in range(LENGTH_OF_TICKET)] + + return "".join(single_ticket_lst) + + result = set() + while len(result) <= NUM_OF_TICKET: + result.add(gen_ticket()) + + print result diff --git a/vvzwvv/0000/0000.py b/vvzwvv/0000/0000.py new file mode 100644 index 00000000..043edf91 --- /dev/null +++ b/vvzwvv/0000/0000.py @@ -0,0 +1,15 @@ +from PIL import Image, ImageDraw, ImageFont + +def add_num(num, fill, font_name): + im = Image.open("in.jpg") + xsize, ysize = im.size + draw = ImageDraw.Draw(im) + text = str(num) + font = ImageFont.truetype(font_name, xsize // 5) + draw.text((ysize // 5 * 4, 0), text, fill, font) + im.save("out.jpg") + +num = 2 +fill = (255, 0, 0) +font_name = "verdana.ttf" +add_num(num, fill, font_name) \ No newline at end of file diff --git a/vvzwvv/0000/in.jpg b/vvzwvv/0000/in.jpg new file mode 100644 index 00000000..c9ecf95d Binary files /dev/null and b/vvzwvv/0000/in.jpg differ diff --git a/vvzwvv/0000/verdana.ttf b/vvzwvv/0000/verdana.ttf new file mode 100644 index 00000000..59f22739 Binary files /dev/null and b/vvzwvv/0000/verdana.ttf differ diff --git a/vvzwvv/0001/0001.py b/vvzwvv/0001/0001.py new file mode 100644 index 00000000..935565cb --- /dev/null +++ b/vvzwvv/0001/0001.py @@ -0,0 +1,14 @@ +import uuid + +def gen(num, len): + L = [] + for i in range(num): + ran = str(uuid.uuid4()).replace('-', '')[:len] + if not ran in L: + L.append(ran) + return L + +if __name__ == '__main__': + for item in gen(200, 16): + print(item) + \ No newline at end of file diff --git a/vvzwvv/0004/0004.py b/vvzwvv/0004/0004.py new file mode 100644 index 00000000..62e49715 --- /dev/null +++ b/vvzwvv/0004/0004.py @@ -0,0 +1,28 @@ +#!/usr/bin/env python +#-*- coding: utf-8 -*- + +import urllib +import re + +def getHtml(url): + page = urllib.urlopen(url) + html = page.read() + return html + +def getImg(html): + # src="http://imgsrc.baidu.com/forum/w%3D580%3Bcp%3Dtieba%2C10%2C302%3Bap%3D%C9%BC%B1%BE%D3%D0%C3%C0%B0%C9%2C90%2C310/sign=8800a2e3b3119313c743ffb855036fa7/1e29460fd9f9d72abb1a7c3cd52a2834349bbb7e.jpg" bdwater= + reg = r'src="(.+?\.jpg)" bdwater=' + img_re = re.compile(reg) + img_list = re.findall(img_re, html) + return img_list + +def saveImg(img_list): + x = 0 + for img_url in img_list: + urllib.urlretrieve(img_url, '%s.jpg' % x) + x += 1 + + +if __name__ == "__main__": + html = getHtml("http://tieba.baidu.com/p/2166231880") + saveImg(getImg(html)) \ No newline at end of file diff --git a/vvzwvv/0010/0010.py b/vvzwvv/0010/0010.py new file mode 100644 index 00000000..04942a8b --- /dev/null +++ b/vvzwvv/0010/0010.py @@ -0,0 +1,42 @@ +#!/usr/bin/env python +#-*- coding: utf-8 -*- + +import string +import random +from PIL import Image, ImageDraw, ImageFont, ImageFilter + +def create_image(image_size = (300, 100), + background_color = (255, 255, 255), + font_type = "arialbd.ttf", + font_size = 50, + text_num = 4, + point_chance = 50): + + im = Image.new("RGB", image_size, background_color) + draw = ImageDraw.Draw(im) + image_width, image_height = image_size + + def create_text(): + text_font = ImageFont.truetype(font_type, font_size) + font_width, font_height = text_font.getsize("A") + for i in range(text_num): + text = random.choice(string.ascii_uppercase) + text_loc = ((image_width - font_width) / text_num * (i + 0.5), (image_height - font_height) / 2.3) + draw.text(text_loc, text, font = text_font, fill = (random.randint(0, 255) / 2, random.randint(0, 255) / 2, random.randint(0, 255) / 2)) + + def create_points(): + for w in range(image_width): + for h in range(image_height): + tmp = random.randint(0, 100) + if tmp > point_chance: + draw.point((w, h), fill = (random.randint(0, 255), random.randint(0, 255), random.randint(0, 255))) + + create_text() + create_points() + im = im.filter(ImageFilter.BLUR) + + return im + +if __name__ == "__main__": + im = create_image() + im.show() diff --git a/vvzwvv/0010/arialbd.ttf b/vvzwvv/0010/arialbd.ttf new file mode 100644 index 00000000..d5fa0e60 Binary files /dev/null and b/vvzwvv/0010/arialbd.ttf differ diff --git a/vvzwvv/0011/0011.py b/vvzwvv/0011/0011.py new file mode 100644 index 00000000..a2398dd7 --- /dev/null +++ b/vvzwvv/0011/0011.py @@ -0,0 +1,22 @@ +from cmd import Cmd + +class CmdCheck(Cmd): + + def __init__(self): + Cmd.__init__(self) + self.intro = "-------- Word Sensor (Input \"exit\" for termination) --------" + self.prompt = "> " + self.sensitive = map(lambda word: word.strip("\n"), open("filtered_words.txt").readlines()) + + def default(self, line): + if any([word in line for word in self.sensitive]): + print "Freedom" + else: + print "Human Rights" + + def do_exit(self, line): + exit() + +if __name__ == "__main__": + cmd = CmdCheck() + cmd.cmdloop() \ No newline at end of file diff --git a/vvzwvv/0011/filtered_words.txt b/vvzwvv/0011/filtered_words.txt new file mode 100644 index 00000000..69373b64 --- /dev/null +++ b/vvzwvv/0011/filtered_words.txt @@ -0,0 +1,11 @@ +北京 +程序员 +公务员 +领导 +牛比 +牛逼 +你娘 +你妈 +love +sex +jiangge \ No newline at end of file diff --git a/vvzwvv/0012/0012.py b/vvzwvv/0012/0012.py new file mode 100644 index 00000000..1b003829 --- /dev/null +++ b/vvzwvv/0012/0012.py @@ -0,0 +1,22 @@ +from cmd import Cmd + +class CmdCheck(Cmd): + + def __init__(self): + Cmd.__init__(self) + self.intro = "-------- Word Sensor (Input \"exit\" for termination) --------" + self.prompt = "> " + self.sensitive = map(lambda word: word.strip("\n"), open("filtered_words.txt").readlines()) + + def default(self, line): + for word in self.sensitive: + if word in line: + line = line.replace(word, ''.join("*" for i in range(len(word)))) + print line + + def do_exit(self, line): + exit() + +if __name__ == "__main__": + cmd = CmdCheck() + cmd.cmdloop() \ No newline at end of file diff --git a/vvzwvv/0012/filtered_words.txt b/vvzwvv/0012/filtered_words.txt new file mode 100644 index 00000000..69373b64 --- /dev/null +++ b/vvzwvv/0012/filtered_words.txt @@ -0,0 +1,11 @@ +北京 +程序员 +公务员 +领导 +牛比 +牛逼 +你娘 +你妈 +love +sex +jiangge \ No newline at end of file diff --git a/xyjxyf/0000/0000.jpg b/xyjxyf/0000/0000.jpg new file mode 100644 index 00000000..1f4d8579 Binary files /dev/null and b/xyjxyf/0000/0000.jpg differ diff --git a/xyjxyf/0004/0004.txt b/xyjxyf/0004/0004.txt new file mode 100644 index 00000000..cf950a09 --- /dev/null +++ b/xyjxyf/0004/0004.txt @@ -0,0 +1,4 @@ + +Henry was a pen name used by an American writer of short stories. + +His real name was William Sydney Porter. diff --git a/xyjxyf/0005/1.jpg b/xyjxyf/0005/1.jpg new file mode 100644 index 00000000..1f4d8579 Binary files /dev/null and b/xyjxyf/0005/1.jpg differ diff --git a/xyjxyf/0005/2.jpg b/xyjxyf/0005/2.jpg new file mode 100644 index 00000000..177dfc8e Binary files /dev/null and b/xyjxyf/0005/2.jpg differ diff --git a/xyjxyf/0006/00061.txt b/xyjxyf/0006/00061.txt new file mode 100644 index 00000000..48ba0476 --- /dev/null +++ b/xyjxyf/0006/00061.txt @@ -0,0 +1,12 @@ + +Henry was a pen name used by an American writer of short stories. + +His + +His + +His + +His + +Henry was a pen name used by an American writer of short stories. diff --git a/xyjxyf/0006/00062.txt b/xyjxyf/0006/00062.txt new file mode 100644 index 00000000..af894a51 --- /dev/null +++ b/xyjxyf/0006/00062.txt @@ -0,0 +1,7 @@ + +Henry was a pen name used by an American writer of short stories. + +His real name was William Sydney Porter. + +pen pen +pen pen pen pen pen pen diff --git a/xyjxyf/0007/stringer.py b/xyjxyf/0007/stringer.py new file mode 100644 index 00000000..56d9d3b3 --- /dev/null +++ b/xyjxyf/0007/stringer.py @@ -0,0 +1,29 @@ +# coding = utf-8 + +import random, string + +/* +sdfhjdsf +hgjh +*/ +# def Unicode(): +# val = random.randint(0x4E00, 0x9FBF) +# return unichr(val) +# +# # 随机汉字 +# def GB2312(): +# head = random.randint(0xB0, 0xCF) +# body = random.randint(0xA, 0xF) +# tail = random.randint(0, 0xF) +# val = ( head << 8 ) | (body << 4) | tail +# str = "%x" % val +# return str.decode('hex').decode('gb2312') + +# 随机字母 +def rand_char(): + return chr(random.randint(65, 90)) + +# 随机字母或者数字 +def rand_choice(): + str = 'abcdefghigklmnopqrstuvwxyzQWERTYUIOPASDFGHJKLZXCVBNM1234567890' + return random.choice(str) diff --git a/xyjxyf/0011/0011.txt b/xyjxyf/0011/0011.txt new file mode 100644 index 00000000..693f4665 --- /dev/null +++ b/xyjxyf/0011/0011.txt @@ -0,0 +1,11 @@ +北京 +程序员 +公务员 +领导 +牛比 +牛逼 +你娘 +你妈 +love +sex +jiangge diff --git a/xyjxyf/0014/student.txt b/xyjxyf/0014/student.txt new file mode 100644 index 00000000..ea9b1593 --- /dev/null +++ b/xyjxyf/0014/student.txt @@ -0,0 +1,5 @@ +{ + "1":["张三",150,120,100], + "2":["李四",90,99,95], + "3":["王五",60,66,68] +} \ No newline at end of file diff --git a/xyjxyf/0014/student.xls b/xyjxyf/0014/student.xls new file mode 100644 index 00000000..b80d5719 Binary files /dev/null and b/xyjxyf/0014/student.xls differ diff --git a/xyjxyf/0015/city.txt b/xyjxyf/0015/city.txt new file mode 100644 index 00000000..312f5c19 --- /dev/null +++ b/xyjxyf/0015/city.txt @@ -0,0 +1,5 @@ +{ + "1" : "上海", + "2" : "北京", + "3" : "成都" +} \ No newline at end of file diff --git a/xyjxyf/0015/city.xls b/xyjxyf/0015/city.xls new file mode 100644 index 00000000..b020435b Binary files /dev/null and b/xyjxyf/0015/city.xls differ diff --git a/xyjxyf/0016/numbers.txt b/xyjxyf/0016/numbers.txt new file mode 100644 index 00000000..c43c0378 --- /dev/null +++ b/xyjxyf/0016/numbers.txt @@ -0,0 +1,5 @@ +[ + [1, 82, 65535], + [20, 90, 13], + [26, 809, 1024] +] \ No newline at end of file diff --git a/xyjxyf/0016/numbers.xls b/xyjxyf/0016/numbers.xls new file mode 100644 index 00000000..091d6ef7 Binary files /dev/null and b/xyjxyf/0016/numbers.xls differ diff --git a/xyjxyf/0017/student.xls b/xyjxyf/0017/student.xls new file mode 100644 index 00000000..b80d5719 Binary files /dev/null and b/xyjxyf/0017/student.xls differ diff --git a/xyjxyf/0017/student.xml b/xyjxyf/0017/student.xml new file mode 100644 index 00000000..55abaffe --- /dev/null +++ b/xyjxyf/0017/student.xml @@ -0,0 +1,14 @@ + + + + + { + 3: ['王五', 60.0, 66.0, 68.0] + 2: ['李四', 90.0, 99.0, 95.0] + 1: ['张三', 150.0, 120.0, 100.0] + } + + diff --git a/xyjxyf/0018/city.xls b/xyjxyf/0018/city.xls new file mode 100644 index 00000000..b020435b Binary files /dev/null and b/xyjxyf/0018/city.xls differ diff --git a/xyjxyf/0018/city.xml b/xyjxyf/0018/city.xml new file mode 100644 index 00000000..00af5e13 --- /dev/null +++ b/xyjxyf/0018/city.xml @@ -0,0 +1,13 @@ + + + + { + 3: ['成都'] + 2: ['北京'] + 1: ['上海'] + } + + + diff --git a/xyjxyf/0019/numbers.xls b/xyjxyf/0019/numbers.xls new file mode 100644 index 00000000..091d6ef7 Binary files /dev/null and b/xyjxyf/0019/numbers.xls differ diff --git a/xyjxyf/0019/numbers.xml b/xyjxyf/0019/numbers.xml new file mode 100644 index 00000000..8a6fcfd0 --- /dev/null +++ b/xyjxyf/0019/numbers.xml @@ -0,0 +1,13 @@ + + + + [ + [1.0, 82.0, 65535.0], + [20.0, 90.0, 13.0], + [26.0, 809.0, 1024.0], + ] + + + diff --git a/xyjxyf/0020/0020.xls b/xyjxyf/0020/0020.xls new file mode 100644 index 00000000..f0d493e5 Binary files /dev/null and b/xyjxyf/0020/0020.xls differ diff --git a/xyjxyf/0025/voice_open_browser.py b/xyjxyf/0025/voice_open_browser.py new file mode 100644 index 00000000..f4127c29 --- /dev/null +++ b/xyjxyf/0025/voice_open_browser.py @@ -0,0 +1,78 @@ +# encoding = utf-8 + +# use pyAudio +# brew install portaudio +# pip install pyaudio + +import wave, pyaudio +from datetime import datetime +from tools import dxbaiduaudio +import webbrowser + +CHUNK = 1024 +FORMAT = pyaudio.paInt16 +RATE = 8000 +CHANNELS = 1 +RECORD_SECONDS = 5 + +def record_wave(to_dir=None): + if to_dir is None: + to_dir = "./" + + pa = pyaudio.PyAudio() + stream = pa.open(format = FORMAT, + channels = CHANNELS, + rate = RATE, + input = True, + frames_per_buffer = CHUNK) + + print("* recording") + + save_buffer = [] + for i in range(0, int(RATE / CHUNK * RECORD_SECONDS)): + audio_data = stream.read(CHUNK) + save_buffer.append(audio_data) + + print("* done recording") + + # stop + stream.stop_stream() + stream.close() + pa.terminate() + + # wav path + file_name = datetime.now().strftime("%Y-%m-%d_%H_%M_%S")+".wav" + if to_dir.endswith('/'): + file_path = to_dir + file_name + else: + file_path = to_dir + "/" + file_name + + # save file + wf = wave.open(file_path, 'wb') + wf.setnchannels(CHANNELS) + wf.setsampwidth(pa.get_sample_size(FORMAT)) + wf.setframerate(RATE) + # join 前的类型 + wf.writeframes(b''.join(save_buffer)) + wf.close() + + return file_path + +def browser_open_text(text): + if text is None: + return + + url = "http://www.baidu.com" + if text.startswith("谷歌") or text.startswith("google"): + url = "http://www.google.com" + elif text.startswith("必应") or text.startswith("bing"): + url = "http://cn.bing.com" + + webbrowser.open_new_tab(url) + +if __name__ == "__main__": + to_dir = "./" + file_path = record_wave(to_dir) + + text = dxbaiduaudio.wav_to_text(file_path) + browser_open_text(text) diff --git a/xyjxyf/README.md b/xyjxyf/README.md new file mode 100644 index 00000000..f579e43b --- /dev/null +++ b/xyjxyf/README.md @@ -0,0 +1,55 @@ +xyjxyf Notes +====== +## Mac上安装Redis + +1. 下载源文件 + +[redis-3.0.7.rar.gz](http://download.redis.io/releases/) + +2. 安装 + +``` +$ tar -zxvf redis-3.0.6.tar.gz +$ cd redis-3.0.7 +$ make test +$ make install +``` + +3. 配置 + +``` +$ vi ./redis.conf + + # 设置为后台运行 +daemonize yes + + # 设置pid文件位置 +pidfile /usr/local/redis/redis.pid + + # 连接超时时间设置为120秒 +timeout 120 + + # 设置日志级别 +loglevel debug + + # 设置日志文件位置 +logfile "/usr/local/redis/log/6379.log" + + # 数据文件所在目录 +dir /usr/local/redis/data/6379 +``` + +4. 启动redis服务器 + +``` +$ ./redis-server +``` + +5. 安装Python的Redis模块 + +我的mac安装了python双版本,用python3 + + +``` +$ pip3 install redis +``` \ No newline at end of file diff --git a/xyjxyf/show_me_the_code.py b/xyjxyf/show_me_the_code.py new file mode 100644 index 00000000..ff3a36d1 --- /dev/null +++ b/xyjxyf/show_me_the_code.py @@ -0,0 +1,622 @@ +# coding = utf-8 + +from tools import imager +from PIL import ImageFont + + +# 第 0000 题:将你的 QQ 头像(或者微博头像)右上角加上红色的数字 +def add_num(image_path): + im = imager.open_image(image_path) + if im is not None: + font = ImageFont.truetype('Arial.ttf', 20) + w, h = im.size + point = (w - 10, 0) + imager.draw_text(im, "8", point, font) + im.show() + + +# 第 0001 题:使用 Python 生成 200 个激活码(或者优惠券) +import uuid + +def create_activation_code(num=200): + codes = [] + for i in range(num): + code = str(uuid.uuid1()) + code = code.replace('-', '') + codes.append(code) + + return codes + + +# 第 0002 题:将 0001 题生成的 200 个激活码(或者优惠券)保存到 MySQL 关系型数据库中。 +import pymysql + +def save_activation_code_to_mysql(): + conn = pymysql.connect(host='localhost', user='root', charset='UTF8') + cur = conn.cursor() + cur.execute("CREATE DATABASE IF NOT EXISTS code_mysql") + cur.execute("USE code_mysql") + cur.execute("CREATE TABLE IF NOT EXISTS codes (id INT, code VARCHAR(255))") + + codes = create_activation_code(200) + for code in codes: + cur.execute("INSERT INTO codes (code) values(%s)", [code]) + + conn.commit() + + cur.execute("SELETE * FROM codes") + data = cur.fetchall() + print("data:%s" % data) + + cur.close() + conn.close() + + +# 第 0003 题:将 0001 题生成的 200 个激活码(或者优惠券)保存到 Redis 非关系型数据库中。 +import redis + +def save_activation_code_to_redis(): + re = redis.Redis(host='127.0.0.1', port=6379, db=0) + + codes = create_activation_code(200) + for code in codes: + re.lpop('codes', code) + + print("data:%s" % re.get('codes')) + + +# 第 0004 题:任一个英文的纯文本文件,统计其中的单词出现的个数。 +import re + +def number_of_words(file_path=None): + num = 0 + + if file_path is None: + return num + + file = open(file_path, 'r') + content = file.read() + content = " " + content + pattern = re.compile(u'\s+\w+') + match = pattern.findall(content) + num = len(match) + + return num + + +# 第 0005 题:你有一个目录,装了很多照片,把它们的尺寸变成都不大于 iPhone5 分辨率的大小。 +def reset_images_size(dir_path=None): + if dir_path is None: + return + + for root, dirs, files in os.walk(dir_path): + for path in files: + if path.startswith("."): + continue + + file_path = os.path.join(root, path) + image = imager.open_image(file_path) + if image is not None: + new_image = imager.reset_image_size(image, 640, 1136) + imager.save(new_image, file_path) + + +# 第 0006 题:你有一个目录,放了你一个月的日记,都是 txt, +# 为了避免分词的问题,假设内容都是英文,请统计出你认为每篇日记最重要的词。 +# 思路:哪个词出现的最多,哪个词就是最重要的词 +import operator + +def get_most_important_word(dir_path=None): + if dir_path is None: + return None + + for root, dirs, files in os.walk(dir_path): + for path in files: + if not path.endswith("txt"): + continue + + file_path = os.path.join(root, path) + content = open(file_path, 'r').read().lower() + + words = content.split() + word_dic = {} + for word in words: + if word in word_dic.keys(): + word_dic[word] += 1 + else: + word_dic[word] = 1 + + if len(word_dic): + word_list = sorted(word_dic.items(), key=lambda x:x[1], reverse=True) + print("%s : %s -- %d" % (path, word_list[0][0], word_list[0][1])) + + + +# 第 0007 题:有个目录,里面是你自己写过的程序,统计一下你写过多少行代码。包括空行和注释,但是要分别列出来 +import os + +# 注释://, #, /* */, """ """, ''' ''' +def lines_of_codes(dir_path=None): + code_num = 0 + note_num = 0 + blank_line_num = 0 + if dir_path is None: + return code_num, note_num, blank_line_num + + for root, dirs, files in os.walk(dir_path): + mut_note = None + for path in files: + if path.startswith("."): + continue + + file_path = os.path.join(root, path) + for count, line in enumerate(open(file_path, "rU")): + + # 判断是否是空行 + if not line.split(): + blank_line_num += 1 + continue + + # 判断是否多行注释 + if mut_note is not None: + note_num += 1 + match_note = re.match("\*/|\"\"\"|\'\'\'", line) + if match_note is not None: + mut_note = None + match_note = re.match("\/\*|\"\"\"|\'\'\'", line) + if match_note is not None: + mut_note = line[match_note.pos:(match_note.endpos - 1)] + + continue + else: + match_note = re.match("\/\*|\"\"\"|\'\'\'", line) + if match_note is not None: + note_num += 1 + mut_note = line[match_note.pos:(match_note.endpos - 1)] + continue + + # 判断单行注释 + match_note1 = re.match("\s*(#|//).*\n*", line) + if match_note1 is not None: + note_num += 1 + continue + + pass + + code_num += count + 1 + + return code_num, note_num, blank_line_num + +# 第 0008 题:一个HTML文件,找出里面的正文 +# 使用 pip install beautifulsoup4 +from bs4 import BeautifulSoup + +def get_html_context(url=None): + if url is None: + return None + + content = request.urlopen(url).read().decode("utf-8") + soup = BeautifulSoup(content) + [script.extract() for script in soup.find_all('script')] + [style.extract() for style in soup.find_all('style')] + + soup.prettify() + reg = re.compile("<[^>]*>") + ret_content = reg.sub('', soup.prettify()) + # print(ret_content) + + return ret_content + + +# 第 0009 题:一个HTML文件,找出里面的链接 +# 查找, 用 HTMLParser +from urllib import request +from tools import dxhtmlparser + +def get_html_links(url=None): + if url is None: + return None + + content = request.urlopen(url).read().decode("utf-8") + dxparser = dxhtmlparser.DXHTMLParser('a', 'href', url) + dxparser.feed(content) + + links = dxparser.getrets() + + return links + +# 第 0010 题:使用 Python 生成字母验证码图片 +def create_verification_code(): + im, str = imager.verification_code() + im.show() + + +# 第 0011 题: 敏感词文本文件 filtered_words.txt,里面的内容为以下内容, +# 北京, 程序员, 公务员, 领导, 牛比, 牛逼, 你娘, 你妈, love, sex, jiangge +# 当用户输入敏感词语时,则打印出 Freedom,否则打印出 Human Rights。 + +def find_sensitive_words(sensitive_file=None, input_string=None): + if sensitive_file is None or input_string is None: + return None + + file = open(sensitive_file, "r") + sensitive_words = file.read().split() + + is_sensitive = False + for sensitive in sensitive_words: + if sensitive in input_string: + is_sensitive = True + print("Freedom") + + if not is_sensitive: + print("Human Rights") + + +# 第 0012 题: 敏感词文本文件 filtered_words.txt,里面的内容 和 0011题一样, +# 当用户输入敏感词语,则用 星号 * 替换,例如当用户输入「北京是个好城市」,则变成「**是个好城市」。 + +def replace_sensitive_words(sensitive_file=None, input_string=None): + if sensitive_file is None or input_string is None: + return None + + file = open(sensitive_file, "r") + sensitive_words = file.read().split() + + for sensitive in sensitive_words: + if sensitive in input_string: + replace_str = "*" * len(sensitive) + input_string = input_string.replace(sensitive, replace_str) + + print(input_string) + +# 第 0013 题: 用 Python 写一个爬图片的程序 +from tools import geturlimgs + +def get_url_imgs(url=None): + if url is None: + return None + + tmp = geturlimgs.geturlimgs() + tmp.get_imgs(url, "/Users/xieyajie/Desktop/Python/ShowMeCode/xyjxyf/0013/") + + + +# 第 0014 题: 纯文本文件 student.txt为学生信息, 写到 student.xls 文件中 +# 第 0015 题: 纯文本文件 city.txt为城市信息,写到 city.xls 文件中 +import json +import xlwt + +def dictxt_to_xls(file_path=None): + if file_path is None: + return + + file = open(file_path, 'r') + if file is None: + return + + content = json.loads(file.read()) + list_data = sorted(content.items(), key=lambda d:d[0]) + + (path, name)=os.path.split(file.name) + file_name = name.split('.')[0] + + wb = xlwt.Workbook() + ws = wb.add_sheet(file_name) + + row = 0 + for item in list_data: + col = 0 + ws.write(row, col, item[0]) + col += 1 + + value = item[1] + if type(value) == list: + for obj in value: + ws.write(row, col, obj) + col += 1 + else: + ws.write(row, col, value) + row += 1 + + save_path = path + "/" + file_name + ".xls" + wb.save(save_path) + + +# 第 0016 题: 纯文本文件 numbers.txt, 请将上述内容写到 numbers.xls 文件中 +def listtxt_to_xls(file_path=None): + if file_path is None: + return + + file = open(file_path) + if file is None: + return + + content = json.loads(file.read()) + content.sort(key=lambda x:x[0]) + + (path, name)=os.path.split(file.name) + file_name = name.split('.')[0] + wb = xlwt.Workbook() + ws = wb.add_sheet(file_name) + + for i in range(len(content)): + col = 0 + list = content[i] + for value in list: + ws.write(i, col, content[i][col]) + col += 1 + + save_path = path + "/" + file_name + ".xls" + wb.save(save_path) + +# pip3 install xlrd +import xlrd +def read_xls(file_path=None): + if file_path is None: + return None + + data_list = {} + wb = xlrd.open_workbook(file_path) + sheet_names = wb.sheet_names() + for name in sheet_names: + table = wb.sheet_by_name(name) + table_data = [] + for i in range(table.nrows): + row_data = table.row_values(i) + table_data.append(row_data) + + data_list[name] = table_data + + return data_list + + +# 第 0017 题: 将 第 0014 题中的 student.xls 文件中的内容写到 student.xml 文件中 +# 使用DOM +from tools import stringer +from xml.dom.minidom import Document + +def write_student_to_xml(dic=None, to_path=None): + if dic is None or to_path is None: + return None + + doc = Document() + root_node = doc.createElement("root") + doc.appendChild(root_node) + + stu_node = doc.createElement("students") + root_node.appendChild(stu_node) + + note_node = doc.createComment("\n\t学生信息表\n\t\"id\" : [名字, 数学, 语文, 英文]\n\t") + stu_node.appendChild(note_node) + + # data = json.dumps(dic, ensure_ascii=False, indent=1) + dic_node = doc.createTextNode(stringer.dict_to_json(dic, "\t\t")) + stu_node.appendChild(dic_node) + + file = open(to_path, "w") + file.write(doc.toprettyxml()) + # doc.writexml(file,' ',' ','\n','utf-8') + file.close() + +# 第 0018 题: 将 第 0015 题中的 city.xls 文件中的内容写到 city.xml 文件中 +# 使用lxml +import codecs +from lxml import etree + +def write_city_to_xml(dic=None, to_path=None): + if dic is None or to_path is None: + return None + + root_node = etree.Element('root') + root_node.text = "\n\t" + + city_node = etree.SubElement(root_node, 'citys') + + comment_node = etree.Comment("\n城市信息\n") + comment_node.tail = "\n\t" + city_node.append(comment_node) + + city_node.text = "\n\t" + stringer.dict_to_json(dic, "\t") + u'\n' + city_node.tail = "\n" + + city_tree = etree.ElementTree(root_node) + city_tree.write(to_path, pretty_print=True, xml_declaration=True, encoding='utf-8') + # output = codecs.open(to_path, 'w', 'utf-8') + # output.write(etree.tounicode(city_tree.getroot())) + # output.close() + + +# 第 0019 题: 将 第 0016 题中的 numbers.xls 文件中的内容写到 numbers.xml 文件中 +def write_numbers_to_xml(list=None, to_path=None): + if list is None or to_path is None: + return None + + root_node = etree.Element('root') + root_node.text = "\n\t" + + number_node = etree.SubElement(root_node, 'numbers') + + comment_node = etree.Comment("\n数字信息\n") + comment_node.tail = "\n\t" + number_node.append(comment_node) + + number_node.text = "\n\t" + stringer.list_to_json(list, "\t") + u'\n' + number_node.tail = "\n" + + number_tree = etree.ElementTree(root_node) + number_tree.write(to_path, pretty_print=True, xml_declaration=True, encoding='utf-8') + + +# 第 0020 题: 登陆中国联通网上营业厅 后选择「自助服务」 --> 「详单查询」,然后选择你要查询的时间段,点击「查询」按钮, +# 查询结果页面的最下方,点击「导出」,就会生成类似于 2014年10月01日~2014年10月31日通话详单.xls 文件。 +# 写代码,对每月通话时间做个统计 + +import datetime + +def statistics_month_time(): + dic = {} + wb = xlrd.open_workbook("./0020/0020.xls") + sheet = wb.sheets()[0] + row_count = sheet.nrows + + for i in range(1, sheet.nrows): + values = sheet.row_values(i) + ym_str = values[2][:6] + + time_str = values[3] + if '时' in time_str: + time_str = re.sub('时', '.', time_str) + if '分' in time_str: + time_str = re.sub('分', '.', time_str) + if '秒' in time_str: + time_str = re.sub('秒', '', time_str) + + tmp = time_str.split('.') + j = len(tmp) - 1 + sum = int(tmp[j]) + while j > -1: + sum = sum + (len(tmp) - 1 - j) * 60 * int(tmp[j]) + j = j - 1 + + if ym_str in dic: + dic[ym_str] = dic[ym_str] + int(sum) + else: + dic[ym_str] = int(sum) + + # i = i + 1 + + return dic + + +# 第 0021 题: 请使用 Python 对密码加密 +from hashlib import sha256 +from hmac import HMAC + +def encrypt_password(password, salt=None): + if salt is None: + salt = os.urandom(8) + + if isinstance(password, str): + password = password.encode('UTF-8') + + ret = password + for i in range(10): + ret = HMAC(ret, salt, sha256).digest() + + return salt + ret + + +# 第 0022 题: iPhone 6、iPhone 6 Plus 早已上市开卖。请查看你写得 第 0005 题的代码是否可以复用 + + +# 第 0023 题: 使用 Python 的 Web 框架,做一个 Web 版本 留言簿 应用 + + +# 第 0024 题: 使用 Python 的 Web 框架,做一个 Web 版本 TodoList 应用 + + +# 第 0025 题: 使用 Python 实现:对着电脑吼一声,自动打开浏览器中的默认网站 +# 在文件夹0025中实现 + + +if __name__ == "__main__": + # 0000 + # add_num(".0000/0000.jpg") + + # 0001 + # create_activation_code() + + # 0002 ????? + # save_activation_code_to_mysql() + + # 0003 + # save_activation_code_to_redis() + + # 0004 + # number_of_words("./0004/0004.txt") + + # 0005 + # reset_images_size("./0005") + + # 0006 + # get_most_important_word("./0006") + + # 0007 + # code, note, blank_line = lines_of_codes("./0007") + # print("代码行数:%i\n注释行数:%i\n空行行数:%i" % (code, note, blank_line)) + + # 0008 + # get_html_context("http://blog.bccn.net") + + # 0009 + # get_html_links("http://blog.bccn.net") + + # 0010 + # create_verification_code() + + # 0011 + # find_sensitive_words("./0011/0011.txt", "haha, 北京不错") + + # 0012 + # replace_sensitive_words("./0011/0011.txt", "haha, 北京不错") + + # 0013 + # get_url_imgs("http://www.ivsky.com/tupian/beijing_t1542/index_2.html") + + # 0014 + # dictxt_to_xls("./0014/student.txt") + + # 0015 + # dictxt_to_xls("./0015/city.txt") + + # 0016 + # listtxt_to_xls("./0016/numbers.txt") + + # 0017 + # student_dic = read_xls("./0017/student.xls") + # for key in student_dic: + # student = student_dic[key] + # + # dic = {} + # for list in student: + # dic[list[0]] = list[1:] + # + # write_student_to_xml(dic, "./0017/student.xml") + # + # break + + + # 0018 + # city_dic = read_xls("./0018/city.xls") + # for key in city_dic: + # city = city_dic[key] + # + # dic = {} + # for list in city: + # dic[list[0]] = list[1:] + # + # write_city_to_xml(dic, "./0018/city.xml") + # + # break + + # 0019 + # number_dic = read_xls("./0019/numbers.xls") + # for key in number_dic: + # number = number_dic[key] + # write_numbers_to_xml(number, "./0019/numbers.xml") + # + # break + + # 0020 + # statistics_month_time() + + # 0021 + encrypt_password("123") + + # 0022 + + # 0023 + + # 0024 + + # 0025 diff --git a/xyjxyf/tools/README.md b/xyjxyf/tools/README.md new file mode 100644 index 00000000..eec10f4a --- /dev/null +++ b/xyjxyf/tools/README.md @@ -0,0 +1,33 @@ +# python_tools + +## imager.py + +图片处理 + +1. 打开 + +2. 保存 + +3. 大小 + +4. 拷贝 + +5. 裁剪 + +6. 压缩 + +7. 添加文字 + +8. 旋转 + +9. 转换色彩模式 + +10. 生成验证码图片 + +## checker.py + +检测指定的内容,可以在Xcode编译时显示警告或者错误提示 + +## replacer.py + +替换指定内容 \ No newline at end of file diff --git a/xyjxyf/tools/__init__.py b/xyjxyf/tools/__init__.py new file mode 100644 index 00000000..e69de29b diff --git a/xyjxyf/tools/colorer.py b/xyjxyf/tools/colorer.py new file mode 100644 index 00000000..6ddcb11c --- /dev/null +++ b/xyjxyf/tools/colorer.py @@ -0,0 +1,24 @@ +# coding = utf-8 + +import random + +def randRGB(min=0, max=255): + if min < 0: + min = 0 + if min > 255: + min = 255 + + if max < 0: + max = 0 + if max > 255: + max = 255 + + if max < min: + tmp = min + min = max + max = tmp + + return (random.randint(min, max), + random.randint(min, max), + random.randint(min, max)) + diff --git a/xyjxyf/tools/dxbaiduaudio.py b/xyjxyf/tools/dxbaiduaudio.py new file mode 100644 index 00000000..0c8a7bf4 --- /dev/null +++ b/xyjxyf/tools/dxbaiduaudio.py @@ -0,0 +1,115 @@ +# encoing = utf-8 + +from urllib import request +import json, base64, uuid, os +import wave +import pycurl +import io + +bda_app_id = "7972313" +bda_api_key = "ZrjLfF5Rh7pOL66gaOmDGnXn" +bda_secret_key = "16bac9645093ca2632ebb81015ff7544" + +bda_access_token = "" +bda_expires_in = "" +ret_text = "" + +def get_mac_address(): + return uuid.UUID(int=uuid.getnode()).hex[-12:] + +def get_access_token(): + url = "https://openapi.baidu.com/oauth/2.0/token?grant_type=client_credentials&client_id=ZrjLfF5Rh7pOL66gaOmDGnXn&client_secret=16bac9645093ca2632ebb81015ff7544" + + req = request.Request(url, method="POST") + resp = request.urlopen(req) + data = resp.read().decode('utf-8') + json_data = json.loads(data) + + global bda_access_token + bda_access_token = json_data['access_token'] + + return bda_access_token + +CHUNK = 1024 +def get_wav_data(wav_path): + if wav_path is None or len(wav_path) == 0: + return None + + fp = wave.open(wav_path, 'rb') + nf = fp.getnframes() + f_len = nf * 2 + audio_data = fp.readframes(nf) + + return audio_data, f_len + +def dump_res(buf): + resp_json = json.loads(buf.decode('utf-8')) + ret = resp_json['result'] + + global ret_text + ret_text = ret[0] + + print(buf) + +def wav_to_text(wav_path): + if wav_path is None or len(wav_path) == 0: + return None + + if len(bda_access_token) == 0: + get_access_token() + if len(bda_access_token) == 0: + return None + + data, f_len = get_wav_data(wav_path) + + url = 'http://vop.baidu.com/server_api?cuid=' + get_mac_address() + '&token=' + bda_access_token + http_header = [ + 'Content-Type: audio/pcm; rate=8000', + 'Content-Length: %d' % f_len + ] + + c = pycurl.Curl() + c.setopt(pycurl.URL, str(url)) #curl doesn't support unicode + #c.setopt(c.RETURNTRANSFER, 1) + c.setopt(c.HTTPHEADER, http_header) #must be list, not dict + c.setopt(c.POST, 1) + c.setopt(c.CONNECTTIMEOUT, 30) + c.setopt(c.TIMEOUT, 30) + c.setopt(c.WRITEFUNCTION, dump_res) + c.setopt(c.POSTFIELDS, data) + c.setopt(c.POSTFIELDSIZE, f_len) + c.perform() #pycurl.perform() has no return val + + return ret_text + + +# def wav_to_text(wav_path): +# if wav_path is None or len(wav_path) == 0: +# return None +# +# wav_data = get_wav_data(wav_path) +# if wav_data is None: +# return None +# +# if len(bda_access_token) == 0: +# get_access_token() +# +# wav_base64 = base64.b64decode(wav_data) +# print("%s", wav_base64) +# # unicode( wav_base64, errors='ignore') +# wav_len = len(wav_data) +# data_dic = {'format':'wav', 'rate':8000, 'channel':1, +# 'cuid':get_mac_address(), 'token':bda_access_token, +# b'speech':wav_base64, 'len':wav_len} +# json_data = json.dumps(data_dic).encode('utf-8') +# json_len = len(json_data) +# +# req = request.Request('http://vop.baidu.com/server_api') +# req.add_header('Content-Type', "application/json") +# req.add_header("Content-Length", json_len) +# resp = request.urlopen(req, data=json_data) +# +# resp_data = resp.read().decode('utf-8') +# resp_json = json.loads(resp_data) +# +# return resp_json['result'] \ No newline at end of file diff --git a/xyjxyf/tools/dxhtmlparser.py b/xyjxyf/tools/dxhtmlparser.py new file mode 100644 index 00000000..49853b6c --- /dev/null +++ b/xyjxyf/tools/dxhtmlparser.py @@ -0,0 +1,23 @@ +# encoding = utf-8 + +from html.parser import HTMLParser + + +class DXHTMLParser(HTMLParser): + def __init__(self, tag, tag_name, url): + HTMLParser.__init__(self) + self.tag = tag + self.tag_name = tag_name + self.url = url + self.rets = [] + + def handle_starttag(self, tag, attrs): + if tag == self.tag: + for name,value in attrs: + if name == self.tag_name: + if value.startswith("/") and len(self.url) > 0: + value = self.url + value + self.rets.append(value) + + def getrets(self): + return self.rets \ No newline at end of file diff --git a/xyjxyf/tools/geturlimgs.py b/xyjxyf/tools/geturlimgs.py new file mode 100644 index 00000000..359bb975 --- /dev/null +++ b/xyjxyf/tools/geturlimgs.py @@ -0,0 +1,66 @@ +# encoding = utf-8 + +import socket, os +from urllib import request +from bs4 import BeautifulSoup + +class geturlimgs(object): + + def __index__(self, to_dir=None): + self.to_dir = None + + # 伪装浏览器,以免被封 + def user_agent(self, url): + req_header = {'User-Agent':'Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US; rv:1.9.1.6) Gecko/20091201 Firefox/3.5.6'} + req_timeout = 20 + try: + req = request.Request(url,None,req_header) + html = request.urlopen(req,None,req_timeout) + except request.URLError as e: + print(e.message) + except socket.timeout as e: + # user_agent(url) + print("timeout") + + return html + + def get_img_links(self, url=None): + if url is None or len(url) == 0: + return None + html = self.user_agent(url) + soup = BeautifulSoup(html, "lxml") + + count = 0 + links = [] + items = soup.find_all('img') + for item in items: + link = item.get('src') + links.append(link) + + return links + + def download_imgs(self, links, to_dir): + if links is None or len(links) == 0: + return + + if not os.path.exists(to_dir): + os.makedirs(to_dir) + + if not to_dir.endswith('/'): + to_dir = to_dir + '/' + + index = 0 + for url in links: + end = os.path.splitext(url)[1] + if len(end) == 0: + end = ".jpg" + img_path = to_dir + '%i%s' % (index, end) + image = request.urlretrieve(url, img_path) + index = index + 1 + + def get_imgs(self, url=None, to_dir=None): + if url is None or to_dir is None: + return None + + links = self.get_img_links(url) + return self.download_imgs(links, to_dir) diff --git a/xyjxyf/tools/imager.py b/xyjxyf/tools/imager.py new file mode 100644 index 00000000..ecb14255 --- /dev/null +++ b/xyjxyf/tools/imager.py @@ -0,0 +1,189 @@ +# coding = utf-8 + +from PIL import Image, ImageDraw, ImageFont, ImageFilter +from tools import colorer, stringer +import types, os + + +# 打开 +def open_image(image_path=None): + if image_path is None or len(image_path) == 0: + return None + + im = Image.open(image_path) + return im + + +# 显示 +def show_image(image_path=None): + im = open_image(image_path) + im.show() + + +# 保存 +def save(image=None, to_path=None): + if image is None or to_path is None or len(to_path) == 0: + return + + f, e = os.path.splitext(to_path) + if e is None or len(e) == 0: + image.save(to_path, "JPEG") + else: + image.save(to_path) + + +# 大小 +def image_size(image=None): + ret_size = (0, 0) + + if image is None: + return ret_size + + return image.size + + +# 拷贝 +def image_copy(image=None): + if image is None: + return None + + return image.copy() + + +# 裁剪 +def image_crop(image=None, box=None): + if image is None or box is None: + return None + + return image.crop(box) + + +# 压缩 +def get_thumb(image=None, ratio=0.6): + if ratio > 1: + return image + if ratio <= 0 or image is None: + return None + + w, h = image.size() + + return image.thumbnail((w * ratio, h * ratio)) + +# # 合并 +# def paste(image=None, sub_image=None, origin=(0, 0)): +# if image is None or sub_image is None: +# return None +# +# im = image +# if type(image) is types.StringType: +# im = Image.open(image) +# if im is None: +# return None +# +# sub_im = sub_image +# if type(sub_image) is types.StringType: +# sub_im = Image.open(sub_image) +# if sub_im is None: +# return None +# +# im_size = im.size +# sub_size = sub_im.size +# # 如果sub_image在image范围内,不需要创建新的图片 +# if origin[0] >= 0 and origin[1] >= 0: +# right = origin[0] + sub_size[0] +# bottom = origin[1] + sub_size[1] +# if right <= im.size[0] and bottom <= im_size[1]: +# return im.paste(sub_im, (origin(0), origin(1), right, bottom)) +# +# right = im_size(0) +# if im_size(0) < sub_size(0): +# width = sub_size(0) +# height = im_size(1) +# if im_size(1) < sub_size(1): +# height = sub_size(1) +# +# +# image = Image.new('RGB', (width, height), (255, 255, 255)) +# +# +# return im.paste(sub_im, box) + + +# 添加文字 +def draw_text(image=None, text=None, origin=(0, 0), font=None, fill='red'): + if image is None or text is None or len(text) == 0: + return None + + context = ImageDraw.Draw(image) + context.text(origin, text, font=font, fill=fill) + return image + + +# 旋转 +def image_rotate(image=None, rotate=0): + + if image is None: + return None + + if rotate == 0: + return image + + return image.rotate(rotate) + + +# 转换色彩模式, mode: 'P'虚化,'L'或者'1'黑白,'LA'怀旧 +def image_convert(image=None, mode='P'): + if image is None: + return None + + return image.convert(mode) + + +# 生成验证码图片:数字和字母 +def verification_code(num=4, width=240, height=60, font_size=30): + image = Image.new('RGB', (width, height), (255, 255, 255)) + font = ImageFont.truetype('Arial.ttf', font_size) + draw = ImageDraw.Draw(image) + + # 背景填充 + for x in range(width): + for y in range(height): + draw.point((x, y), colorer.randRGB(min=64)) + + # 文字 + tw = width / num + margin = (tw - font_size) / 2 + ty = (height - font_size) / 2 + tx = margin + str = "" + for t in range(num): + char = stringer.rand_char() + draw.text((tx, ty), char, font=font, fill=colorer.randRGB(0, 100)) + tx = tx + tw + str = str + char + + # 模糊效果 + image = image.filter(ImageFilter.BLUR) + + return image, str + +# 生成中文验证码 + +# 重置图片大小 +def reset_image_size(image=None, max_width=None, max_height=None): + if image is None or max_width is None or max_height is None: + return + + if image.size[0] <= max_width and image.size[1] <= max_height: + return + + rotate = image.size[0] / image.size[1] + if rotate > 1: + new_width = max_width + new_height = max_width / rotate + else: + new_height = max_height + new_width = max_height * rotate + + new_image = image.resize((int(new_width), int(new_height)), Image.BILINEAR) + return new_image diff --git a/xyjxyf/tools/stringer.py b/xyjxyf/tools/stringer.py new file mode 100644 index 00000000..546dce86 --- /dev/null +++ b/xyjxyf/tools/stringer.py @@ -0,0 +1,76 @@ +# coding = utf-8 + +import random, string + +# def Unicode(): +# val = random.randint(0x4E00, 0x9FBF) +# return unichr(val) +# +# # 随机汉字 +# def GB2312(): +# head = random.randint(0xB0, 0xCF) +# body = random.randint(0xA, 0xF) +# tail = random.randint(0, 0xF) +# val = ( head << 8 ) | (body << 4) | tail +# str = "%x" % val +# return str.decode('hex').decode('gb2312') + +# 随机字母 +def rand_char(): + return chr(random.randint(65, 90)) + +# 随机字母或者数字 +def rand_choice(): + str = 'abcdefghigklmnopqrstuvwxyzQWERTYUIOPASDFGHJKLZXCVBNM1234567890' + return random.choice(str) + +# 将字典转为json格式 +def dict_to_json(object=None, begin_indent="", indent=u'\t', newl=u'\n'): + if object is None: + return None + + if type(object) is not dict: + return None + + ret_str = u'{' + newl + space = begin_indent + indent + for key in object: + ret_str = ret_str + space + key + ": " + item = object[key] + ret_str = ret_str + u'%s,' % str(item) + # if type(item) is list: + # list_to_json(item) + # elif type(item) is dict: + # dict_to_json(item) + # else: + # str + ret_str = ret_str + begin_indent + newl + + ret_str = ret_str + begin_indent + u'}' + + return ret_str + + +# 将数组转为json格式 +def list_to_json(object=None, begin_indent="", indent=u'\t', newl=u'\n'): + if object is None: + return None + + if type(object) is not list: + return None + + ret_str = u'[' + newl + space = begin_indent + indent + for item in object: + ret_str = ret_str + space + u'%s,' % str(item) + # if type(item) is list: + # list_to_json(item) + # elif type(item) is dict: + # dict_to_json(item) + # else: + # str + ret_str = ret_str + begin_indent + newl + + ret_str = ret_str + begin_indent + u']' + + return ret_str \ No newline at end of file diff --git a/xyjxyf/tools/test.py b/xyjxyf/tools/test.py new file mode 100644 index 00000000..52a91f05 --- /dev/null +++ b/xyjxyf/tools/test.py @@ -0,0 +1,6 @@ +# coding = utf-8 + +from tools import imager + +im, str = imager.verification_code() +im.show() \ No newline at end of file diff --git a/yefan/001/001.py b/yefan/001/001.py new file mode 100644 index 00000000..278a307a --- /dev/null +++ b/yefan/001/001.py @@ -0,0 +1,43 @@ +#!/usr/bin/env python +# -*- coding: utf-8 -*- + +""" +分析 +其实要生成激活码(邀请码)也是很简单的事, 比如随机生成.或者使用GUID,UUID等,非常简单 + +但是我们得考虑存入以及验证的问题. + +这里我参考产生唯一随机码的方法分析。这篇文章的思路: + +主键+随机码的方式. + +这种方法优点:使用也比较简单,不用直接去查询数据库,而最大的优点是查询的时候,可以根据邀请码直接得到主键id, 然后根据id去数据库查询(速度很快),再比较查询出来的邀请码和用户提交的邀请码是否一致。 + +生成:id(数据库primary key )->16进制 + "L(标识符)" +随机码 +获取id:获取16进制的id再转回10进制 +""" + + +import random +import string + +def activation_code(id,length=10): + ''' + id + L + 随机码 + string模块中的3个函数:string.letters,string.printable,string.printable + ''' + prefix = hex(int(id))[2:]+ 'L' + length = length - len(prefix) + chars=string.ascii_letters+string.digits + return prefix + ''.join([random.choice(chars) for i in range(length)]) + +def get_id(code): + ''' Hex to Dec ''' + return str(int(code.upper(), 16)) + +if __name__=="__main__": + for i in range(10,500,35): + code = activation_code(i) + id_hex = code.split('L')[0] + id = get_id(id_hex) + print code,id diff --git a/yefan/004/004.py b/yefan/004/004.py new file mode 100644 index 00000000..f6eac70f --- /dev/null +++ b/yefan/004/004.py @@ -0,0 +1,24 @@ +#!/usr/bin/env python +# -*- coding: utf-8 -*- + +""" +python实现任一个英文的纯文本文件,统计其中的单词出现的个数、行数、字符数 +""" + +file_name = "movie.txt" + +line_counts = 0 +word_counts = 0 +character_counts = 0 + +with open('C:\Python27\oneday_one\movie.txt', 'r') as f: + for line in f: + words = line.split() + + line_counts += 1 + word_counts += len(words) + character_counts += len(line) + +print "line_counts ", line_counts +print "word_counts ", word_counts +print "character_counts ", character_counts diff --git a/yefan/007/007.py b/yefan/007/007.py new file mode 100644 index 00000000..d19f1406 --- /dev/null +++ b/yefan/007/007.py @@ -0,0 +1,40 @@ +# -*- coding: utf-8 -*- + + +#list all the files in your path(完整路径名path\**.py) +import os +def get_files(path): + files=os.listdir(path) + files_path=[] + for fi in files: + fi_path= path+'\\' + fi + if os.path.isfile(fi_path): + if fi.split('.')[-1]=='py': + files_path.append(fi_path) + elif(os.path.isdir(fi_path)): + files_path+=get_files(fi_path) + return files_path + +# Count lines and blank lines and note lines in designated files +def count_lines(files): + line, blank, note = 0, 0, 0 + for filename in files: + f = open(filename, 'rb') + for l in f: + l = l.strip() + line += 1 + if l == '': + blank += 1 + elif l[0] == '#' or l[0] == '/': + note += 1 + f.close() + return (line, blank, note) + +if __name__ == '__main__': + a=r'c:\python27' + #files = get_files(r'c:\python27\oneday_one') + files = get_files(r'F\v6:') + print len(files),files + lines = count_lines(files) + print 'Line(s): %d, black line(s): %d, note line(s): %d' % (lines[0], lines[1], lines[2]) + diff --git a/yefan/008/008.py b/yefan/008/008.py new file mode 100644 index 00000000..1bebe4da --- /dev/null +++ b/yefan/008/008.py @@ -0,0 +1,19 @@ +#!/usr/bin/python +#coding=utf-8 + +""" +第 0008 题:一个HTML文件,找出里面的正文。 +""" + +from bs4 import BeautifulSoup + +def find_the_content(path): + with open(path) as f: + text = BeautifulSoup(f, 'lxml') + content = text.get_text().strip('\n') + + return content.encode('gbk','ignore') + + +if __name__ == '__main__': + print find_the_content(r'D:\Show-Me-the-Code_show-me-the-code_1.html') diff --git a/yefan/009/009.py b/yefan/009/009.py new file mode 100644 index 00000000..14c8ec00 --- /dev/null +++ b/yefan/009/009.py @@ -0,0 +1,20 @@ +#!/usr/bin/python +#coding=utf-8 + +""" +第 0009 题:一个HTML文件,找出里面的链接 +""" + +from bs4 import BeautifulSoup + +def find_the_link(filepath): + links = [] + with open(filepath) as f: + bs =BeautifulSoup(f,'lxml') + for i in bs.find_all('a'): + links.append(i['href']) + return links + +if __name__ == '__main__': + #print find_the_link('D:\Show-Me-the-Code_show-me-the-code_1.html') + diff --git a/yefan/011/011.py b/yefan/011/011.py new file mode 100644 index 00000000..df43c831 --- /dev/null +++ b/yefan/011/011.py @@ -0,0 +1,28 @@ +#!/bin/env python +# -*- coding: utf-8 -*- +import codecs +def read_txt(): + l=[] + with codecs.open(r'c:\python27\oneday_one\1.txt') as fp: + for line in fp.readlines(): + l.append(line.strip()) + return l + +def check(l): + word=raw_input('word:') + for each_word in l: + if word==each_word: + print 'Freedom' + return None + print 'Human rights' + return None + +def main(): + l=read_txt() + check(l) + print l + +if __name__=='__main__': + main() + + diff --git a/yefan/013/013.py b/yefan/013/013.py new file mode 100644 index 00000000..cd5e8167 --- /dev/null +++ b/yefan/013/013.py @@ -0,0 +1,39 @@ +#!/usr/bin/python +# coding=utf-8 + +""" +第 0013 题: 用 Python 写一个爬图片的程序,爬 这个链接里的日本妹子图片 :-) +""" + +import os +import urllib +from bs4 import BeautifulSoup +from urlparse import urlsplit +import re + +def catch_tieba_pics(url): + content =urllib.urlopen(url) + print type(content) + #f.write(content.read()) + bs = BeautifulSoup(content, 'lxml') + print type(bs) + print bs.prettify() ################ + for i in bs.find_all('img', {"class": "BDE_Image"}): + download_pic(i['src']) + +def download_pic(url): + image_content = urllib.urlopen(url).read() + file_name = os.path.basename(urlsplit(url)[2]) + output = open(file_name, 'wb') + output.write(image_content) + output.close() + + +if __name__ == '__main__': + #catch_tieba_pics('http://tieba.baidu.com/p/2166231880') + catch_tieba_pics('http://tieba.baidu.com/p/4203526008') + #catch_tieba_pics('http://www.zhihu.com/question/22995735') + +""" +为什么知乎的网页print内容只有一点点 +""" diff --git a/yefan/014/014.py b/yefan/014/014.py new file mode 100644 index 00000000..3a5ae5c2 --- /dev/null +++ b/yefan/014/014.py @@ -0,0 +1,17 @@ +# coding = utf-8 +__author__ = 'Forec' +import xlwt +import re + +book = xlwt.Workbook(encoding = 'utf-8', style_compression=0) +sheet = book.add_sheet('student',cell_overwrite_ok = True) +line = 0 +info = re.compile(r'\"(\d+)\":\[\"(.*?)\",(\d+),(\d+),(\d+)\]') +with open('student.txt',"r") as f: + data = f.read() + data=data.decode('gbk').encode('utf-8') +for x in info.findall(data): + for i in range(len(x)): + sheet.write(line,i,x[i]) + line+=1 +book.save('student.xls') diff --git a/yefan/014/14.py b/yefan/014/14.py new file mode 100644 index 00000000..18acf36d --- /dev/null +++ b/yefan/014/14.py @@ -0,0 +1,41 @@ +#!/bin/env python +# -*- coding: utf-8 -*- + +#导入模块 +import simplejson as json +import xlwt + +#从文件(JSON形式)中读取数据返回字典 +def read_file(filename): + with open(r'C:\Python27\oneday_one\student.txt','r') as fp: + content = fp.read().decode('gbk').encode('utf-8') + #print type(content) + #simplejson这个模块还没细看,怎么解码还是需要了解下 + d = json.JSONDecoder().decode(content) + #d=json.loads(content) + return d + +#生成对应的xls文件 +def gen_xls(d,filename): + fp = xlwt.Workbook() + table = fp.add_sheet('student',cell_overwrite_ok=True) + #试了下,与很多要转utf-8(ASCII码)存文件的情况不同,xls不接受ASCII码形式的存储,直接用字典里面的Unicode就行了,简直好评,不用在特意decode或者encode了 + #想写得更加自动化一些,好复用.本身不太想用两层循环的,不过也不知道有没有更便捷的存储方式(比如整行自动匹配导入,算法是背后优化封装好的,就用了万能的这种方法) + for n in range(len(d)): + table.write(n,0,n+1) + m = 0 + for record in d[str(n+1)]: + table.write(n,m+1,record) + m += 1 + fp.save('student.xls') + print u'写入完毕' + +#主函数,嘛,最后还是用“丑陋的二重循环”实现了,但是其实也没什么,还是要看场景和优化,毕竟这也不是做查找或者排序,在日常使用中也不用太担心性能问题 +def main(): + filename = 'student.txt' + xls_name = 'student.xls' + d = read_file(filename) + gen_xls(d,xls_name) + +if __name__ == '__main__': + main() diff --git a/yefan/014/student.txt b/yefan/014/student.txt new file mode 100644 index 00000000..ddb4a149 --- /dev/null +++ b/yefan/014/student.txt @@ -0,0 +1,5 @@ +{ + "1":["",150,120,100], + "2":["",90,99,95], + "3":["",60,66,68] +} \ No newline at end of file diff --git a/yefan/014/student.xls b/yefan/014/student.xls new file mode 100644 index 00000000..c392c6f5 Binary files /dev/null and b/yefan/014/student.xls differ diff --git a/yefan/015/015.py b/yefan/015/015.py new file mode 100644 index 00000000..79fb4590 --- /dev/null +++ b/yefan/015/015.py @@ -0,0 +1,16 @@ +# coding = utf-8 +__author__ = 'Forec' +import xlwt +import re + +book = xlwt.Workbook(encoding = 'utf-8',style_compression=0) +sheet = book.add_sheet('number',cell_overwrite_ok = True) +line = 0 +info = re.compile(r'\[(\d+),\s+(\d+),\s+(\d+)\]') +with open(r'c:\python27\oneday_one\numbers.txt',"r") as f: + data = f.read().decode('gbk').encode('utf-8') +for x in info.findall(data): + for i in range(len(x)): + sheet.write(line,i,x[i]) + line+=1 +book.save('numbers.xls') diff --git a/yefan/015/city.txt b/yefan/015/city.txt new file mode 100644 index 00000000..4d62a75c --- /dev/null +++ b/yefan/015/city.txt @@ -0,0 +1,5 @@ +{ + "1" : "Ϻ", + "2" : "", + "3" : "ɶ" +} \ No newline at end of file diff --git a/yefan/015/city.xls b/yefan/015/city.xls new file mode 100644 index 00000000..b020435b Binary files /dev/null and b/yefan/015/city.xls differ diff --git a/yefan/020/020.py b/yefan/020/020.py new file mode 100644 index 00000000..4f8cf398 --- /dev/null +++ b/yefan/020/020.py @@ -0,0 +1,26 @@ +#-*- coding=utf-8 +import xlwt +import xlrd +import re + +book = xlrd.open_workbook(r'c:\python27\oneday_one\2015.xls') +print book.sheet_names() +sheet=book.sheet_by_index(0) +print sheet.name,sheet.nrows,sheet.ncols +col3=sheet.col_values(3) +li=[] +for i in col3: + li.append(i)#.encode('utf-8') +del li[0] +s=[0,0] +info=re.compile(ur"(\d+)[\u4e00-\u9fa5](\d*)[\u4e00-\u9fa5]*")#匹配汉字!!!! +for each_time in li: + t=info.match(each_time).groups() + t=list(t) + if u'' in t: + t[1],t[0]=t[0],u'0' + s[0]=s[0]+int(t[0]) + s[1]=s[1]+int(t[1]) +s[0],s[1]=s[0]+int(s[1]/60),s[1]%60 +print '通话时长累计%d分%d秒'%(s[0],s[1]) + diff --git a/yefan/020/2015.xls b/yefan/020/2015.xls new file mode 100644 index 00000000..f0d493e5 Binary files /dev/null and b/yefan/020/2015.xls differ diff --git a/yefan/README.md b/yefan/README.md new file mode 100644 index 00000000..fdc2f54a --- /dev/null +++ b/yefan/README.md @@ -0,0 +1 @@ +所有程序是在win7 python2.7下调试成功,其中很多借鉴了此项目下其他贡献者的代码。侵删。 diff --git a/JiYouMCC/0023/guestbook/manage.py b/zentst/0023/manage.py old mode 100755 new mode 100644 similarity index 61% rename from JiYouMCC/0023/guestbook/manage.py rename to zentst/0023/manage.py index d04c7217..8a50ec04 --- a/JiYouMCC/0023/guestbook/manage.py +++ b/zentst/0023/manage.py @@ -1,9 +1,9 @@ -# -*- coding: utf-8 -*- +#!/usr/bin/env python import os import sys if __name__ == "__main__": - os.environ.setdefault("DJANGO_SETTINGS_MODULE", "guestbook.settings") + os.environ.setdefault("DJANGO_SETTINGS_MODULE", "mysite.settings") from django.core.management import execute_from_command_line diff --git a/zentst/0023/messageboard/__init__.py b/zentst/0023/messageboard/__init__.py new file mode 100644 index 00000000..e69de29b diff --git a/zentst/0023/messageboard/admin.py b/zentst/0023/messageboard/admin.py new file mode 100644 index 00000000..11cb9f27 --- /dev/null +++ b/zentst/0023/messageboard/admin.py @@ -0,0 +1,13 @@ +from django.contrib import admin +from messageboard.models import Message + + + +class MessageAdmin(admin.ModelAdmin): + fieldsets = [ + (None,{'fields':['name']}), + ('context',{'fields':['context']}), + ] + list_display = ('name', 'context', 'vote_date') + +admin.site.register(Message, MessageAdmin) diff --git a/zentst/0023/messageboard/models.py b/zentst/0023/messageboard/models.py new file mode 100644 index 00000000..bd8d96a2 --- /dev/null +++ b/zentst/0023/messageboard/models.py @@ -0,0 +1,12 @@ +from django.db import models + +# Create your models here. + +class Message(models.Model): + name = models.CharField(max_length = 20) + context = models.CharField(max_length = 200) + vote_date = models.DateTimeField(auto_now_add = True) + + def __unicode__(self): + return self.context + diff --git a/zentst/0023/messageboard/templates/message/detail.html b/zentst/0023/messageboard/templates/message/detail.html new file mode 100644 index 00000000..ff63d703 --- /dev/null +++ b/zentst/0023/messageboard/templates/message/detail.html @@ -0,0 +1,6 @@ +for test +{{messages}} +{% for each in messages %} +
  • {{each}}
  • +{%endfor%} + diff --git a/zentst/0023/messageboard/templates/message/index.html b/zentst/0023/messageboard/templates/message/index.html new file mode 100644 index 00000000..804769b2 --- /dev/null +++ b/zentst/0023/messageboard/templates/message/index.html @@ -0,0 +1,63 @@ + + + + +留言薄 + + +
    + + +{% if error_message %} +

    {{error_message}}

    + + +{% else %} + +
    +{% csrf_token %} +请尽情留言吧 +
    +
    + + + + + + + +
    姓名
    内容
    +
    + +
    +
    + + +

    历史留言

    +
      +{% for each in messages %} +
    1. {{each.name}} 留言于 ({{each.vote_date}})

      +
      +

      {{each.context}}

    2. + +{%endfor%} +
    + +{% endif %} + + + + + + + + diff --git a/zentst/0023/messageboard/tests.py b/zentst/0023/messageboard/tests.py new file mode 100644 index 00000000..501deb77 --- /dev/null +++ b/zentst/0023/messageboard/tests.py @@ -0,0 +1,16 @@ +""" +This file demonstrates writing tests using the unittest module. These will pass +when you run "manage.py test". + +Replace this with more appropriate tests for your application. +""" + +from django.test import TestCase + + +class SimpleTest(TestCase): + def test_basic_addition(self): + """ + Tests that 1 + 1 always equals 2. + """ + self.assertEqual(1 + 1, 2) diff --git a/zentst/0023/messageboard/urls.py b/zentst/0023/messageboard/urls.py new file mode 100644 index 00000000..24ba1fc5 --- /dev/null +++ b/zentst/0023/messageboard/urls.py @@ -0,0 +1,10 @@ +from django.conf.urls import patterns, include, url +from messageboard import views +from django.views.generic import ListView +from messageboard.models import Message + + +urlpatterns = patterns('', + url(r'^$', views.index, name = 'index'), + url(r'^postmessage/$', views.postmessage, name = 'postmessage'), +) diff --git a/zentst/0023/messageboard/views.py b/zentst/0023/messageboard/views.py new file mode 100644 index 00000000..42698c09 --- /dev/null +++ b/zentst/0023/messageboard/views.py @@ -0,0 +1,28 @@ +from django.http import HttpResponseRedirect +from django.template import Context +from django.shortcuts import render +from django.utils import timezone +from django.core.urlresolvers import reverse +from messageboard.models import Message +from django.views.decorators.csrf import csrf_exempt + +# Create your views here. +@csrf_exempt +def index(request): + messages = Message.objects.all().order_by('-vote_date') + context = {'messages' : messages,} + return render(request, 'message/index.html', context) + + +def postmessage(request): + postname = request.POST['name'] + postcontext = request.POST['context'] + if postname == '': + return render(request, 'message/index.html', {'error_message' : 'You did not input your name',}) + elif postcontext == '': + return render(request, 'message/index.html', {'error_message' : 'You did not input context',}) + else: + m = Message(name = postname, context = postcontext, vote_date = timezone.now()) + m.save() + return HttpResponseRedirect(reverse('index')) + diff --git a/zentst/0023/mysite/__init__.py b/zentst/0023/mysite/__init__.py new file mode 100644 index 00000000..e69de29b diff --git a/zentst/0023/mysite/settings.py b/zentst/0023/mysite/settings.py new file mode 100644 index 00000000..b68a0164 --- /dev/null +++ b/zentst/0023/mysite/settings.py @@ -0,0 +1,161 @@ +# Django settings for mysite project. + +DEBUG = True +TEMPLATE_DEBUG = DEBUG + +ADMINS = ( + # ('Your Name', 'your_email@example.com'), +) + +MANAGERS = ADMINS + +DATABASES = { + 'default': { + 'ENGINE': 'django.db.backends.sqlite3', # Add 'postgresql_psycopg2', 'mysql', 'sqlite3' or 'oracle'. + 'NAME': 'D:/workspace/mysite/sqlite3.db', # Or path to database file if using sqlite3. + # The following settings are not used with sqlite3: + 'USER': '', + 'PASSWORD': '', + 'HOST': '', # Empty for localhost through domain sockets or '127.0.0.1' for localhost through TCP. + 'PORT': '', # Set to empty string for default. + } +} + +# Hosts/domain names that are valid for this site; required if DEBUG is False +# See https://docs.djangoproject.com/en/1.5/ref/settings/#allowed-hosts +ALLOWED_HOSTS = [] + +# Local time zone for this installation. Choices can be found here: +# http://en.wikipedia.org/wiki/List_of_tz_zones_by_name +# although not all choices may be available on all operating systems. +# In a Windows environment this must be set to your system time zone. +TIME_ZONE = 'GMT+8' + +# Language code for this installation. All choices can be found here: +# http://www.i18nguy.com/unicode/language-identifiers.html +LANGUAGE_CODE = 'en-us' + +SITE_ID = 1 + +# If you set this to False, Django will make some optimizations so as not +# to load the internationalization machinery. +USE_I18N = True + +# If you set this to False, Django will not format dates, numbers and +# calendars according to the current locale. +USE_L10N = True + +# If you set this to False, Django will not use timezone-aware datetimes. +USE_TZ = True + +# Absolute filesystem path to the directory that will hold user-uploaded files. +# Example: "/var/www/example.com/media/" +MEDIA_ROOT = '' + +# URL that handles the media served from MEDIA_ROOT. Make sure to use a +# trailing slash. +# Examples: "http://example.com/media/", "http://media.example.com/" +MEDIA_URL = '' + +# Absolute path to the directory static files should be collected to. +# Don't put anything in this directory yourself; store your static files +# in apps' "static/" subdirectories and in STATICFILES_DIRS. +# Example: "/var/www/example.com/static/" +STATIC_ROOT = '' + +# URL prefix for static files. +# Example: "http://example.com/static/", "http://static.example.com/" +STATIC_URL = '/static/' + +# Additional locations of static files +STATICFILES_DIRS = ( + # Put strings here, like "/home/html/static" or "C:/www/django/static". + # Always use forward slashes, even on Windows. + # Don't forget to use absolute paths, not relative paths. +) + +# List of finder classes that know how to find static files in +# various locations. +STATICFILES_FINDERS = ( + 'django.contrib.staticfiles.finders.FileSystemFinder', + 'django.contrib.staticfiles.finders.AppDirectoriesFinder', +# 'django.contrib.staticfiles.finders.DefaultStorageFinder', +) + +# Make this unique, and don't share it with anybody. +SECRET_KEY = 'wm-!t8*l0+5yq-##j=(%&^2ns0bw=h@r=5!b9%3(63by^7-pg&' + +# List of callables that know how to import templates from various sources. +TEMPLATE_LOADERS = ( + 'django.template.loaders.filesystem.Loader', + 'django.template.loaders.app_directories.Loader', +# 'django.template.loaders.eggs.Loader', +) + +MIDDLEWARE_CLASSES = ( + 'django.middleware.common.CommonMiddleware', + 'django.contrib.sessions.middleware.SessionMiddleware', + 'django.middleware.csrf.CsrfViewMiddleware', + 'django.contrib.auth.middleware.AuthenticationMiddleware', + 'django.contrib.messages.middleware.MessageMiddleware', + # Uncomment the next line for simple clickjacking protection: + # 'django.middleware.clickjacking.XFrameOptionsMiddleware', +) + +ROOT_URLCONF = 'mysite.urls' + +# Python dotted path to the WSGI application used by Django's runserver. +WSGI_APPLICATION = 'mysite.wsgi.application' + +TEMPLATE_DIRS = ( + # Put strings here, like "/home/html/django_templates" or "C:/www/django/templates". + # Always use forward slashes, even on Windows. + # Don't forget to use absolute paths, not relative paths. + 'D:/workspace/mysite/templates', + +) + +INSTALLED_APPS = ( + 'django.contrib.auth', + 'django.contrib.contenttypes', + 'django.contrib.sessions', + 'django.contrib.sites', + 'django.contrib.messages', + 'django.contrib.staticfiles', + # Uncomment the next line to enable the admin: + 'django.contrib.admin', + # Uncomment the next line to enable admin documentation: + # 'django.contrib.admindocs', + 'messageboard', +) + +SESSION_SERIALIZER = 'django.contrib.sessions.serializers.JSONSerializer' + +# A sample logging configuration. The only tangible logging +# performed by this configuration is to send an email to +# the site admins on every HTTP 500 error when DEBUG=False. +# See http://docs.djangoproject.com/en/dev/topics/logging for +# more details on how to customize your logging configuration. +LOGGING = { + 'version': 1, + 'disable_existing_loggers': False, + 'filters': { + 'require_debug_false': { + '()': 'django.utils.log.RequireDebugFalse' + } + }, + 'handlers': { + 'mail_admins': { + 'level': 'ERROR', + 'filters': ['require_debug_false'], + 'class': 'django.utils.log.AdminEmailHandler' + } + }, + 'loggers': { + 'django.request': { + 'handlers': ['mail_admins'], + 'level': 'ERROR', + 'propagate': True, + }, + } +} diff --git a/zentst/0023/mysite/urls.py b/zentst/0023/mysite/urls.py new file mode 100644 index 00000000..8e14e7af --- /dev/null +++ b/zentst/0023/mysite/urls.py @@ -0,0 +1,18 @@ +from django.conf.urls import patterns, include, url + +# Uncomment the next two lines to enable the admin: +from django.contrib import admin +admin.autodiscover() + +urlpatterns = patterns('', + # Examples: + # url(r'^$', 'mysite.views.home', name='home'), + # url(r'^mysite/', include('mysite.foo.urls')), + + # Uncomment the admin/doc line below to enable admin documentation: + # url(r'^admin/doc/', include('django.contrib.admindocs.urls')), + + # Uncomment the next line to enable the admin: + url(r'^admin/', include(admin.site.urls)), + url(r'^messageboard/', include('messageboard.urls')),), +) diff --git a/zentst/0023/mysite/wsgi.py b/zentst/0023/mysite/wsgi.py new file mode 100644 index 00000000..34e900eb --- /dev/null +++ b/zentst/0023/mysite/wsgi.py @@ -0,0 +1,32 @@ +""" +WSGI config for mysite project. + +This module contains the WSGI application used by Django's development server +and any production WSGI deployments. It should expose a module-level variable +named ``application``. Django's ``runserver`` and ``runfcgi`` commands discover +this application via the ``WSGI_APPLICATION`` setting. + +Usually you will have the standard Django WSGI application here, but it also +might make sense to replace the whole Django WSGI application with a custom one +that later delegates to the Django one. For example, you could introduce WSGI +middleware here, or combine a Django application with an application of another +framework. + +""" +import os + +# We defer to a DJANGO_SETTINGS_MODULE already in the environment. This breaks +# if running multiple sites in the same mod_wsgi process. To fix this, use +# mod_wsgi daemon mode with each site in its own daemon process, or use +# os.environ["DJANGO_SETTINGS_MODULE"] = "mysite.settings" +os.environ.setdefault("DJANGO_SETTINGS_MODULE", "mysite.settings") + +# This application object is used by any WSGI server configured to use this +# file. This includes Django's development server, if the WSGI_APPLICATION +# setting points here. +from django.core.wsgi import get_wsgi_application +application = get_wsgi_application() + +# Apply WSGI middleware here. +# from helloworld.wsgi import HelloWorldApplication +# application = HelloWorldApplication(application) diff --git a/JiYouMCC/0024/todoList/db.sqlite3 b/zentst/0023/sqlite3.db similarity index 55% rename from JiYouMCC/0024/todoList/db.sqlite3 rename to zentst/0023/sqlite3.db index 09e30819..0a97b2e4 100644 Binary files a/JiYouMCC/0024/todoList/db.sqlite3 and b/zentst/0023/sqlite3.db differ diff --git a/zeyue/0007/ComputeCodeLines.py b/zeyue/0007/ComputeCodeLines.py new file mode 100644 index 00000000..a67b6e09 --- /dev/null +++ b/zeyue/0007/ComputeCodeLines.py @@ -0,0 +1,221 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- +""" +File: ComputeCodeLines.py +Author: Zeyue Liang +Date: September 2, 2015 +Email: zeyue.liang@gmail.com +Github: https://github.com/zeyue +Description: + A program that can count code line numbers in a directory. + Usage: Launce the program in console with directory as argument, it can add + several directories in one time: + $python -3 ComputeCodeLines.py [second] [...] + ATTENTION: use "/" in the place of "\" + + This program has been tested using some files in C and in Python, + maybe support java as well. +""" + +import os +import sys + +""" +Global variables +""" +file_suffix = "not defined" +inline_comment_syntax = "not defined" +start_comment_syntax = "not defined" +end_comment_syntax = "not defined" +multilineCommentStartFlag = 0 +result = {"Code files": 0, + "No blank lines": 0, + "Code lines": 0, + "Comment lines": 0, + "Blank lines": 0} + + +""" +Funcitions +""" + + +def getFilesList(directory): + """Get files's list in a directory + + :directory: files' directory + :returns: file path list + + """ + file_paths = [] + + for root, directories, files in os.walk(directory): + for filename in files: + file_path = os.path.join(root, filename) + file_paths.append(file_path) + + return file_paths + + +def getSuffix(full_file_path): + """Get the suffix of current file. + + :full_file_path: path of one file + :returns: suffix + + """ + return os.path.splitext(full_file_path)[1][1:] + + +def identifyFileType(suffix): + """Identify the file type and return correct syntax. + + :suffix: file suffix + :returns: [inline comment syntax, multiple line comment syntax] + + """ + if suffix == "py": + return "#", "\"\"\"", "\"\"\"" + elif suffix == "c" or suffix == "h" or suffix == "cpp" or suffix == "hpp": + return "//", "/*", "*/" + elif suffix == "java": + return "//", "/*", "*/" + else: + return "not defined" + + +def isInlineComment(string_line): + """Check if string line is an inline comment or not. + + :string_line: input line + :returns: true or false + + """ + commentLen = len(inline_comment_syntax) + if string_line[0:commentLen] == inline_comment_syntax: + # print("zero") + return True + else: + return False + + +def isMultilineComment(string_line): + """Check if the string line is a multiple comment or not. + + :string_line: one string line in the file + :returns: True or False + + """ + global multilineCommentStartFlag + commentLen = len(str(start_comment_syntax)) + # print(multilineCommentStartFlag) + if(string_line[0:commentLen] == start_comment_syntax and + multilineCommentStartFlag == 0): + multilineCommentStartFlag = 1 + # print("one") + if(len(string_line) > commentLen and + string_line[-commentLen:] == end_comment_syntax): + multilineCommentStartFlag = 0 + return True + elif(string_line[0:commentLen] != start_comment_syntax and + multilineCommentStartFlag == 1): + # print("two") + if(len(string_line) > commentLen and + string_line[-commentLen:] == end_comment_syntax): + multilineCommentStartFlag = 0 + return True + elif(string_line[-commentLen:] == end_comment_syntax and + multilineCommentStartFlag == 1): + multilineCommentStartFlag = 0 + # print("three") + # print(string_line[-commentLen:]) + return True + else: + return False + + +def countOneFile(full_file_path): + """Count code lines in one file. + + :full_file_path: full path of the file + :returns: null + + """ + global inline_comment_syntax, start_comment_syntax, end_comment_syntax + global multilineCommentStartFlag + local_result = {"No blank lines": 0, + "Comment lines": 0, + "Code lines": 0, + "Blank lines": 0} + file_suffix = getSuffix(full_file_path) + if(identifyFileType(file_suffix) != "not defined"): + result["Code files"] += 1 + (inline_comment_syntax, + start_comment_syntax, + end_comment_syntax) = identifyFileType(file_suffix) + with open(full_file_path, "r") as lines: + for line in lines: + line = line.strip() + if line.strip(): + local_result["No blank lines"] += 1 + if isInlineComment(line): + local_result["Comment lines"] += 1 + elif isMultilineComment(line): + local_result["Comment lines"] += 1 + else: + # print("Oops...") + local_result["Code lines"] += 1 + else: + local_result["Blank lines"] += 1 + print(full_file_path) + for key in local_result: + print(str(key) + ": " + str(local_result[key])) + result["No blank lines"] += local_result["No blank lines"] + result["Comment lines"] += local_result["Comment lines"] + result["Code lines"] += local_result["Code lines"] + result["Blank lines"] += local_result["Blank lines"] + + +def countInDirectory(directory): + """Count code lines in one directory. + + :directory: the directory that will be counted + :return: null + + """ + full_file_paths = getFilesList(directory) + for f in full_file_paths: + countOneFile(f) + + +def main(): + """main function. + + """ + global file_suffix, inline_comment_syntax, start_comment_syntax + global end_comment_syntax, multilineCommentStartFlag, result + for directory in sys.argv[1:]: + file_suffix = "not defined" + inline_comment_syntax = "not defined" + start_comment_syntax = "not defined" + end_comment_syntax = "not defined" + multilineCommentStartFlag = 0 + result = {"Code files": 0, + "No blank lines": 0, + "Code lines": 0, + "Comment lines": 0, + "Blank lines": 0} + + print("this is the directory: " + directory) + countInDirectory(directory) + + print() + print("Final result in the directory") + print(directory) + for key in result: + print(str(key) + ": " + str(result[key])) + +""" +Launch +""" +main() diff --git a/zeyue/0007/README.md b/zeyue/0007/README.md new file mode 100644 index 00000000..3b350d47 --- /dev/null +++ b/zeyue/0007/README.md @@ -0,0 +1,42 @@ +**Description:** This program is a simple program in python to count code lines in one or several directories. It will distinguish: + + 1. code lines + 2. blank lines + 3. comment lines + 4. total non-blank lines + + > for now, I suppose to count inline comment and multiple lines comment as well. + + > `#` and `'''` in python; `//` and `/**/` in C/C++ + +**Supported file types:** + + .py, .c, .cpp, .h, .hpp. + > These 4 types have been tested, should be supposed to work well. Otherwise, `.java` maybe work as well, but not yet tested. + +**Usage:** This program should be launched through console, indicating directories that you want to count within. The command line is like this: + + python -3 ComputeCodeLines.py [Full path of first directory] [Full path of second directory] [...] +**Example:**I have a directory in `d:/PythonProjects/python/zeyue/0007`. So my command line will be: + + python -3 ComputeCodeLines.py d:/PythonProjects/python/zeyue/0007 +> **ATTENTION:** In the directory path, the slash `/` or `\\` is necessary. **DO NOT** use `\` + +And I get a response like this: + + this is the directory: d:\PythonProjects\python\zeyue\0007 + d:\PythonProjects\python\zeyue\0007\ComputeCodeLines.py + Blank lines: 41 + Code lines: 117 + Comment lines: 63 + No blank lines: 180 + () + Final result in the directory + d:\PythonProjects\python\zeyue\0007 + Code files: 1 + Code lines: 117 + Comment lines: 63 + No blank lines: 180 + Blank lines: 41 + +That's it! Hope you enjoyful!