diff --git a/.gitignore b/.gitignore index e345e14..6d8b4cf 100644 --- a/.gitignore +++ b/.gitignore @@ -1,139 +1,10 @@ -# Byte-compiled / optimized / DLL files -__pycache__/ -*.py[cod] -*$py.class - -# C extensions -*.so - -# Distribution / packaging -.Python -env/ -build/ -develop-eggs/ -dist/ -downloads/ -eggs/ -.eggs/ -lib/ -lib64/ -parts/ -sdist/ -var/ -*.egg-info/ -.installed.cfg -*.egg - -# PyInstaller -# Usually these files are written by a python script from a template -# before PyInstaller builds the exe, so as to inject date/other infos into it. -*.manifest -*.spec - -# Installer logs -pip-log.txt -pip-delete-this-directory.txt - -# Unit test / coverage reports -htmlcov/ -.tox/ -.coverage -.coverage.* -.cache -nosetests.xml -coverage.xml -*,cover -.hypothesis/ - -# Translations -*.mo -*.pot - -# Django stuff: +.idea +*.pyc +*.swp +*.swo +*.pyo *.log -local_settings.py - -# Flask instance folder -instance/ - -# Scrapy stuff: -.scrapy - -# Sphinx documentation -docs/_build/ - -# PyBuilder -target/ - -# IPython Notebook -.ipynb_checkpoints - -# pyenv -.python-version - -# celery beat schedule file -celerybeat-schedule - -# dotenv -.env - -# virtualenv -venv/ -ENV/ - -# Spyder project settings -.spyderproject - -# Rope project settings -.ropeproject - -# ========================= -# Operating System Files -# ========================= - -# OSX -# ========================= - -.DS_Store -.AppleDouble -.LSOverride - -# Thumbnails -._* - -# Files that might appear in the root of a volume -.DocumentRevisions-V100 -.fseventsd -.Spotlight-V100 -.TemporaryItems -.Trashes -.VolumeIcon.icns - -# Directories potentially created on remote AFP share -.AppleDB -.AppleDesktop -Network Trash Folder -Temporary Items -.apdisk - -# Windows -# ========================= - -# Windows image file caches -Thumbs.db -ehthumbs.db - -# Folder config file -Desktop.ini - -# Recycle Bin used on file shares -$RECYCLE.BIN/ - -# Windows Installer files -*.cab -*.msi -*.msm -*.msp +*.DS_Store -# Windows shortcuts -*.lnk +abc.out +nohup.out \ No newline at end of file diff --git a/.idea/Python-Study.iml b/.idea/Python-Study.iml new file mode 100644 index 0000000..6f63a63 --- /dev/null +++ b/.idea/Python-Study.iml @@ -0,0 +1,12 @@ + + + + + + + + + + \ No newline at end of file diff --git a/.idea/dictionaries/wangjianfeng2014.xml b/.idea/dictionaries/wangjianfeng2014.xml new file mode 100644 index 0000000..3fa06e8 --- /dev/null +++ b/.idea/dictionaries/wangjianfeng2014.xml @@ -0,0 +1,3 @@ + + + \ No newline at end of file diff --git a/.idea/misc.xml b/.idea/misc.xml new file mode 100644 index 0000000..f9edad6 --- /dev/null +++ b/.idea/misc.xml @@ -0,0 +1,14 @@ + + + + + + + + + + + + + + \ No newline at end of file diff --git a/.idea/modules.xml b/.idea/modules.xml new file mode 100644 index 0000000..e05c456 --- /dev/null +++ b/.idea/modules.xml @@ -0,0 +1,8 @@ + + + + + + + + \ No newline at end of file diff --git a/.idea/vcs.xml b/.idea/vcs.xml new file mode 100644 index 0000000..94a25f7 --- /dev/null +++ b/.idea/vcs.xml @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/.idea/workspace.xml b/.idea/workspace.xml new file mode 100644 index 0000000..cc00740 --- /dev/null +++ b/.idea/workspace.xml @@ -0,0 +1,648 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + true + DEFINITION_ORDER + + + + + + + + + + + + + + AngularJS + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + project + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 1467015422705 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/1.txt b/1.txt new file mode 100644 index 0000000..e69de29 diff --git a/Class-Cocacola.py b/Class-Cocacola.py new file mode 100644 index 0000000..af3bccb --- /dev/null +++ b/Class-Cocacola.py @@ -0,0 +1,36 @@ +#!usr/bin/env python3 +# -*- coding: utf-8 -*- + +' test ' + +_author_='wangjianfeng' + +class Cocacola: + calories=140 + sodium=45 + total_carb=39 + caffeine=34 + ingredients=[ + 'high fructose corn syrup', + 'carbonated water ', + 'phosphoric acid', + 'natural flavors', + 'caramel color', + 'caffeine' + ] + def __init__(self,logo_name): + self.local_logo=logo_name + def drink(self): + print('you got {} cal energy !'.format(self.calories)) +class CaffeineFree(Cocacola): + caffeine=0 + ingredients=[ + 'high fructose corn syrup', + 'carbonated water ', + 'phosphoric acid', + 'natural flavors', + 'caramel color', + ] +coke_a=CaffeineFree('Cocacola-free') +coke_a.drink() + diff --git a/Class-Enum.py b/Class-Enum.py new file mode 100644 index 0000000..360a227 --- /dev/null +++ b/Class-Enum.py @@ -0,0 +1,34 @@ +#!usr/bin/env python3 +# -*- coding: utf-8 -*- + +'use enum' + +_author_='wangjianfeng' + +from enum import Enum,unique + +Month=Enum('Month',('Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec')) +for name,member in Month.__members__.items():#注意前后member不一样 + print(name,'=>',member,',',member.value) + +@unique#Decorator unique可以帮助我们检查保证没有重复值 +class Weekday(Enum): + Sun=0#sun value set 0 + Mon=1 + Tue=2 + Wed=3 + Thu=4 + Fri=5 + Sat=6 +day1=Weekday.Mon +print('day1=',day1) +print(Weekday.Tue) +print(Weekday['Tue']) +print(Weekday.Tue.value) +print(Weekday.Mon==day1) +print(day1==Weekday.Tue) +print(Weekday(1)) +print(Weekday(1)==day1) + +for name,member in Weekday.__members__.items(): + print(name,'=>',member) diff --git a/Class-Metaclass.py b/Class-Metaclass.py new file mode 100644 index 0000000..103561e --- /dev/null +++ b/Class-Metaclass.py @@ -0,0 +1,23 @@ +#!usr/bin/env python3 +# -*- coding: utf-8 -*- + +'元类' + +_author_='wangjianfeng' + + +'type()函数 function' +#Hello=type('Hello',(object,),dict(hello=fn))#创建HEllo Class + +'metaclass' +#metaclass 是类的模板,所以必须从‘type’派生 +class ListMetaclass(type): + def __new__(cls,name,bases,attrs): + attrs['add']=lambda self,value:self.append(value) + return type.__new__(cls,name,bases,attrs) +class Mylist(list,metaclass=ListMetaclass): + pass +'test' +L=Mylist() +L.add(1) +print(L) \ No newline at end of file diff --git a/Class-MixIN.py b/Class-MixIN.py new file mode 100644 index 0000000..ba43a94 --- /dev/null +++ b/Class-MixIN.py @@ -0,0 +1,31 @@ +#!/usr/bin/env python3 +# -*- coding:utf-8 -*- + +' Mixin ' + +_author_='wangjianfeng' + +class Animal(object): + pass +#大类 +class Mammal(Animal): + pass +class Bird(Animal): + pass +class Runnable(object): + def run(self): + print('running...') +class Flyable(object): + def fly(self): + print('flying...') +#all kinds of animal python可以多重继承但是JAVA不可以只能单一继承 +class Dog(Mammal,Runnable): + pass +class Cat(Mammal): + pass +class Parrot(Bird): + pass +class Ostrich(Bird,Runnable): + pass +class Bat(Bird,Flyable,Mammal): + pass diff --git a/Class-instance-private.py b/Class-instance-private.py new file mode 100644 index 0000000..11d7e2a --- /dev/null +++ b/Class-instance-private.py @@ -0,0 +1,31 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- + +'class instance private' + +_author_='wangjianfeng' + +class Student: + def __init__(self,name,score): + self.__name=name#加入————确保了属性的访问限制,变为一个私有属性,只有内部可以访问 + self.__score=score + def print_score(self): + print('{}:{}'.format(self.__name,self.__score)) + def get_grade(self): + if self.__score >=90: + return 'A' + elif self.__score >=60: + return 'B' + else: + return 'C' + def get_name(self):#获取名字 + return self.__name + def get_score(self):#获取分数 + return self.__score + def set_score(self,score):#设置分数 + if 0<=score<=100: + self.__score=score + else: + raise ValueError('bad score') +bart=Student('wangjianfeng',89) + diff --git a/Class-metaclass-create ORM.py b/Class-metaclass-create ORM.py new file mode 100644 index 0000000..0a04211 --- /dev/null +++ b/Class-metaclass-create ORM.py @@ -0,0 +1,68 @@ +#!usr/bin/env python3 +# -*- coding: utf-8 -*- + +'metaclass create a ORM frameworks' + +_author_='wangjianfeng' + +class Field(object): + def __init__(self,name,column_type): + self.name=name + self.column_type=column_type + def __str__(self): + return '<%s:%s>'%(self.__class__.__name__,self.name) + +class StringField(Field): + def __init__(self,name): + super(StringField,self).__init__(name,'varchar(100)') + +class IntegerField(Field): + def __init__(self,name): + super(IntegerField, self).__init__(name,'bigint') + +class ModelMetaclass(type): + def __new__(cls, name, bases,attrs): + if name=='Model': + return type.__new__(cls,name,bases,attrs) + print('Found Model:%s'%name) + mappings=dict() + for k,v in attrs.items(): + if isinstance(v,Field): + print('Found mapping:%s==>%s'%(k,v)) + mappings[k]=v + for k in mappings.keys(): + attrs.pop(k) + attrs['__mappings__']=mappings#保存列和属性的映射关系 + attrs['__table__']=name#假设表名和类名一致 + return type.__new__(cls,name,bases,attrs) +class Model(dict,metaclass=ModelMetaclass): + def __init__(self,**kw): + super(Model, self).__init__(**kw) + def __getattr__(self, key): + try: + return self[key] + except KeyError: + raise AttributeError (r"'Model'object has no attribute '%s'"%key) + def __setattr__(self, key, value): + self[key]=value + def save(self): + fields=[] + params=[] + args=[] + for k,v in self.__mappings__.items(): + fields.append(v.name) + params.append('?') + args.append(getattr(self,k,None)) + sql='insert into%s (%s) values(%s)'%(self.__table__,','.join(fields),','.join(params)) + print('SQL:%s'%sql) + print('ARGS:%s'%str(args)) + +'test' +class User(Model): + #定义类的属性到列的映射 + id=IntegerField('id') + name=StringField('name') + email=StringField('email') + password=StringField('password') +u=User(id=12345,name='Michael',email='test@org.com',password='my-pwd') +u.save() \ No newline at end of file diff --git a/Class-property.py b/Class-property.py new file mode 100644 index 0000000..590441c --- /dev/null +++ b/Class-property.py @@ -0,0 +1,30 @@ +#!/usr/bin/env python3 +# -*- coding:utf-8 -*- + +' property ' + +_author_='wangjianfeng' + +class Screen(object): + @property + def width(self): + return self._width + @width.setter + def width(self,value): + self._width=value + @property + def height(self): + return self._height + @height.setter + def height(self,value): + self._height=value + @property + def resolution(self): + return self._width*self._height +#test +s=Screen() +s.height=1024 +s.width=768 +print(s.resolution) +#测试代码正确与否 +assert s.resolution == 786432, '1024 * 768 = %d ?' % s.resolution \ No newline at end of file diff --git a/Class-slot.py b/Class-slot.py new file mode 100644 index 0000000..0aca0a0 --- /dev/null +++ b/Class-slot.py @@ -0,0 +1,14 @@ +#!usr/bin/env python3 +# -*- coding: utf-8 -*- + +' _slot ' + +_author_='wangjianfeng' + +class Student(object): + _slot_=('name','age')#use tuple定义允许绑定的属性名称 +s=Student() +s.name='wang' +s.age=26 +s.score=99 +print(s.score) \ No newline at end of file diff --git a/Class-special_class.py b/Class-special_class.py new file mode 100644 index 0000000..69a0175 --- /dev/null +++ b/Class-special_class.py @@ -0,0 +1,40 @@ +#!/usr/bin/env python3 +# -*- coding:utf-8 -*- + +' special class ' + +_author_='wangjianfeng' + +'__iter__'#这样class可以用for循环,迭代 +class Fib(object): + def __init__(self): + self.a,self.b=0,1#初始化 + def __iter__(self): + return self#实例本身就是迭代对象,故返回自身 + def __next__(self): + self.a,self.b=self.b,self.a+self.b#计算下一个值 + if self.a>10000: + raise StopIteration + return self.a + def __getitem__(self):#可以让class具有list的slice function + pass +for n in Fib(): + print(n) +#__getatter__可以搞链式调用,这个不太理解 +class Chain(object): + + def __init__(self, path=''): + self._path = path + def __getattr__(self, path): + return Chain('%s/%s' % (self._path, path)) + def __str__(self): + return self._path + __repr__ = __str__ +#__call__可以调用了自身的方法,另外可以用callable判断一个对象是否可以调用 +class Student(object): + def __init__(self,name): + self.name=name + def __call__(self): + print('my name is %s'%self.name) +s=Student('wangjianfeng') +s() \ No newline at end of file diff --git a/Collections.py b/Collections.py new file mode 100644 index 0000000..81ea3f7 --- /dev/null +++ b/Collections.py @@ -0,0 +1,31 @@ +#!usr/bin/env python3 +# -*- coding: utf-8 -*- + +'collections' + +_author_='wangjianfeng' + +from collections import namedtuple,deque,defaultdict,OrderedDict,Counter + +#namedtuple用法 +Point=namedtuple('Point',['x','y']) +p=Point(1,2) + +#deque +q=deque(['a','b','c']) +q.append('x') +q.appendleft('y')#appendleft() popleft()可以高效的头部添加和删除 +print(q) + +#defaultdict 引用dict时候如果key不存在的话会出现keyerrror,如果希望key不存在的话可以返回一个默认值,就可以用defaultdict +dd=defaultdict(lambda:'N/A') +dd['key1']= 'abc' +print(dd['key1']) +print(dd['key2']) + +#OrderedDict 可以让dict保持顺序 +#counter简单的计数器 +c=Counter() +for ch in 'programming': + c[ch]=c[ch]+1 +print(c) \ No newline at end of file diff --git a/Crawler-TBMM.py b/Crawler-TBMM.py new file mode 100644 index 0000000..04b4af8 --- /dev/null +++ b/Crawler-TBMM.py @@ -0,0 +1,34 @@ +#!/usr/bin/env python3 +# -*- coding:utf-8 -*- + +'crawler taobaomm' + +_author_='wangjianfeng' + +import re + +old_url='http://www.jikexueyuan.com/course/android/?pageNum=2' +total_page = 20 + +with open('text.txt','r',encoding='utf-8') as f: + html=f.read() + # print(html) +#获取标题 +title=re.search('(.*?)',html,re.S).group(1) +print(title) + +#match url +# link=re.findall('href="(.*?)"',html,re.S) +# for i in link: +# print(i) + +# large first +text_filed=re.findall('',html,re.S)[0] +the_text=re.findall('">(.*?)',text_filed,re.S) +for every_text in the_text: + print(every_text) + +#sub 实现翻页 +for i in range(2,total_page+1): + new_link=re.sub('pageNum=\d+','pageNum=%d'%i,old_url,re.S) + print(new_link) \ No newline at end of file diff --git a/Datatime.py b/Datatime.py new file mode 100644 index 0000000..c5b062d --- /dev/null +++ b/Datatime.py @@ -0,0 +1,29 @@ +#!usr/bin/env python3 +# -*- coding: utf-8 -*- + +'datatime' + +_author_='wangjianfeng' + +from datetime import datetime,timedelta +now=datetime.now() +print(now) +print(type(now)) + +dt=datetime(2015,4,6,12,20) +print(dt) +print(dt.timestamp())#转换为timestamp标准时间 + +t=1428294000.0 +print(datetime.fromtimestamp(t)) #转本地时间 +print(datetime.utcfromtimestamp(t))#转为UTC时间 + +#str 互换datetime +print(now.strftime('%a,%b %d %H:%M'))#时间转STR +cday=datetime.strptime('2016-6-1 18:15:20','%Y-%m-%d %H:%M:%S')#str to time +print(cday) +print('----------------') +#时间加减 +print(now+timedelta(hours=10)) +print(now+timedelta(days=1)) +print(now+timedelta(days=2,hours=12)) \ No newline at end of file diff --git a/Datetime-test.py b/Datetime-test.py new file mode 100644 index 0000000..3da5591 --- /dev/null +++ b/Datetime-test.py @@ -0,0 +1,27 @@ +#!usr/bin/env python3 +# -*- coding: utf-8 -*- + +' datetime-test ' + +_author_='wangjianfeng' + +import re +from datetime import datetime,timedelta,timezone + +def to_timestamp(dt_str,tz_str): + #使用strptime活得datetime + dt=datetime.strptime(dt_str,'%Y-%m-%d %H:%M:%S') + #利用正则表达式获取timezone,并且利用int和zone使其变为整数 + #tz=timezone(timedelta(hours=int(''.join(re.match(r'UTC([\+|\-])(\d{1,2})', tz_str).groups())))) + tz=timezone(timedelta(hours=int(''.join(re.match(r'UTC([\+|\-])(\d{1,2})', tz_str).groups())))) + dt=dt.replace(tzinfo=tz) + return dt.timestamp() +# 测试: + +t1 = to_timestamp('2015-6-1 08:10:30', 'UTC+7:00') +assert t1 == 1433121030.0, t1 + +t2 = to_timestamp('2015-5-31 16:10:30', 'UTC-09:00') +assert t2 == 1433121030.0, t2 + +print('Pass') diff --git a/Debug.py b/Debug.py new file mode 100644 index 0000000..60c5920 --- /dev/null +++ b/Debug.py @@ -0,0 +1,22 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- + +'subject' + +_author_='wangjianfeng' + +import logging +import pdb +def foo(s): + n=int(s) + assert n!=0,'n is zeor' + return 10/0 + +def main(): + foo('0') + +s='0' +n=int(s) +pdb.set_trace() +logging.info('n=%d'%n) +print(10/n) \ No newline at end of file diff --git a/Default parameter to slove power.py b/Default parameter to slove power.py new file mode 100644 index 0000000..72889f7 --- /dev/null +++ b/Default parameter to slove power.py @@ -0,0 +1,11 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- + +' default parameter to slove power' + +_author_='wangjianfeng' + +#设置默认参数来求解多次方 +def power(x,n=1): + return x**n +print(power(5,3)) diff --git a/Error Processing.py b/Error Processing.py new file mode 100644 index 0000000..085b9f6 --- /dev/null +++ b/Error Processing.py @@ -0,0 +1,35 @@ +#!usr/bin/env python3 +# -*- coding: utf-8 -*- + +'try except' + +_author_='wangjianfeng' + +import logging + +try: + print('try....') + r=10/2 + print('result is',r) +#不同的except抓取不同的错误 +except ValueError as e: + print('ValueError',e) +except ZeroDivisionError as e: + print('except:',e) +else:#当没有错误时候输出 + print('NO Error') +finally: + print('Finally...') +print('——————————————————————————') + +def foo(s): + return 10/0 +def bar(s): + return foo(s)*2 +def main(): + try: + bar('0') + except Exception as e: + logging.exception(e) +main() +print('*************') \ No newline at end of file diff --git a/Filter.py b/Filter.py new file mode 100644 index 0000000..f925263 --- /dev/null +++ b/Filter.py @@ -0,0 +1,93 @@ +<<<<<<< HEAD +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- + +' filter ' + +_author_='wangjianfeng' + +def is_odd(n): + return n%2==0 +print(list(filter(is_odd,[1,2,3,4,5,6,7,8,9,10]))) + +def not_empty(s): + return s and s.strip() +print(list(filter(not_empty,['a','b',None,'c',' ']))) + +#filter prime number +#define a odd number sequence +def _odd_iter(): + n=1 + while True: + n=n+2 + yield n +#define a filter +def _not_divisible(n): + return lambda x:x%n>0 +#define a generator +def primes(): + yield 2 + it=_odd_iter()#初始化序列 + while True: + n=next(it)#返回序列的第一个数 + yield n + it=filter(_not_divisible(n),it)#构造新数列 +#打印1000以内的素数 +for n in primes(): + if n<100: + print(n) + else: + break + +#过滤掉非回数 +def is_palindrome(n): + return str(n)[::-1]==str(n) +output=filter(is_palindrome,range(1,10000)) +print(list(output)) +======= +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- + +' filter ' + +_author_='wangjianfeng' + +def is_odd(n): + return n%2==0 +print(list(filter(is_odd,[1,2,3,4,5,6,7,8,9,10]))) + +def not_empty(s): + return s and s.strip() +print(list(filter(not_empty,['a','b',None,'c',' ']))) + +#filter prime number +#define a odd number sequence +def _odd_iter(): + n=1 + while True: + n=n+2 + yield n +#define a filter +def _not_divisible(n): + return lambda x:x%n>0 +#define a generator +def primes(): + yield 2 + it=_odd_iter()#初始化序列 + while True: + n=next(it)#返回序列的第一个数 + yield n + it=filter(_not_divisible(n),it)#构造新数列 +#打印1000以内的素数 +for n in primes(): + if n<100: + print(n) + else: + break + +#过滤掉非回数 +def is_palindrome(n): + return str(n)[::-1]==str(n) +output=filter(is_palindrome,range(1,10000)) +print(list(output)) +>>>>>>> origin/Base diff --git a/HTMLParser-test.py b/HTMLParser-test.py new file mode 100644 index 0000000..fe9cdd4 --- /dev/null +++ b/HTMLParser-test.py @@ -0,0 +1,11 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- + +'htmlparser test' + +_author_='wangjianfeng' + +from html.parser import HTMLParser +from html.entities import name2codepoint + +class \ No newline at end of file diff --git a/HTMLParser.py b/HTMLParser.py new file mode 100644 index 0000000..5969fb8 --- /dev/null +++ b/HTMLParser.py @@ -0,0 +1,32 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- + +'HtmlParser' + +_author_='wangjianfeng' + +from html.parser import HTMLParser +from html.entities import name2codepoint + +class MyHTMLParser(HTMLParser): + def handle_starttag(self,tag,attrs): + print('<%s>'%tag) + def handle_endtag(self, tag): + print('<%s>'%tag) + def handle_startendtag(self, tag, attrs): + print('<%s>'%tag) + def handle_data(self, data): + print(data) + def handle_comment(self, data): + print('') + def handle_entityref(self, name): + print('&%s'%name) + def handle_charref(self, name): + print('#&%s'%name) +parser=MyHTMLParser() +parser.feed(''' + + + +

Some html HTML tutorial...
END

+''') diff --git a/Hashlib.py b/Hashlib.py new file mode 100644 index 0000000..5cf1ff0 --- /dev/null +++ b/Hashlib.py @@ -0,0 +1,21 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- + +'hashlib' + +_author_='wangjianfeng' + +import hashlib + +#MD5算法(生成结果是固定的128bit字节,通常用一个32位的16进制的字符串表示 +md5=hashlib.md5() +md5.update('how to use md5 in python hashlib?'.encode('utf-8')) +#分块调用 +#md5.update('how to use md5 in '.encode('utf-8')) +#md5.update('python hashlib?'.encode('utf-8')) +print(md5.hexdigest()) + +#SHA1算法-生成一个160bit字节,通常用一个10位的16进制的字符串表示 +sha1=hashlib.sha1() +sha1.update('how to use md5 in python hashlib?'.encode('utf-8')) +print(sha1.hexdigest()) diff --git a/Iterator.py b/Iterator.py new file mode 100644 index 0000000..aebb8c0 --- /dev/null +++ b/Iterator.py @@ -0,0 +1,15 @@ +#!usr/bin/env python3 +# -*- coding: utf-8 -*- + +' Iterator ' + +_author_='wangjianfeng' + +#judgement +from collections import Iterable +print(isinstance([],Iterable)) +print(isinstance({},Iterable)) + +#using iter() function make others become iterable +#list dict str is iterable but not a iter +print(isinstance(iter([]),Iterable)) \ No newline at end of file diff --git a/Itertools.py b/Itertools.py new file mode 100644 index 0000000..5f48ebb --- /dev/null +++ b/Itertools.py @@ -0,0 +1,28 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- + +'itertools' + +_author_='wangjianfeng' + +import itertools +''' +natuals=itertools.count(1)#创建的无限迭代器,注意停止 +#for i in natuals: +# print(i) +ts=itertools.takewhile(lambda x: x<=10,natuals)#takewhile截取数据 +print(list(ts)) + +#cycle会把传入的序列不断迭代 +cs=itertools.cycle('abc') +for c in cs: + print(c) + +#repeat 可以把一个元素无线重复下去,第二个参数可以控制重复次数 +ns=itertools.repeat('a',3) +for n in ns: + print(n) +''' +#chain +for c in itertools.chain('BCD','344'): + print(c) diff --git a/Manipulate files and directories.py b/Manipulate files and directories.py new file mode 100644 index 0000000..5245fd3 --- /dev/null +++ b/Manipulate files and directories.py @@ -0,0 +1,31 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- + +'system' + +_author_='wangjianfeng' + +import os +print(os.name)#获取计算机操作系统类型 +#print(os.uname)#获取操作系统详细信息 在win上面不支持·· +print(os.environ)#获取环境变量 +print('----------------------------------') +print(os.path.abspath('.')) +#在某个目录下创建一个新的目录,首先先把新目录的完整路径表现出来 +os.path.join('D:\\学习\GitHub\Python-Study\\','testdir') +#然后创建一个目录 +os.mkdir('D:\\学习\GitHub\Python-Study\\testdir') +#然后删除目录 +os.rmdir('D:\\学习\GitHub\Python-Study\\testdir') + +#拆分路径 +print(os.path.split('C:\\Users\wangjianfeng2014\Desktop\my file.txt')) +print(os.path.splitext('C:\\Users\wangjianfeng2014\Desktop\my file.txt')) +#重命名和删除 +#os.rename('test.py','test.py') +#os.remove('test.py') + +#列出当前目录下的所有目录 +print([x for x in os.listdir('.') if os.path.isdir(x)]) +#列出所有py file +print([x for x in os.listdir('.') if os.path.isfile(x) and os.path.splitext(x)[1]=='.py']) diff --git a/Multiprocessing.py b/Multiprocessing.py new file mode 100644 index 0000000..5143839 --- /dev/null +++ b/Multiprocessing.py @@ -0,0 +1,44 @@ +#!usr/bin/env python3 +# -*- coding: utf-8 -*- + +' multiprocessing' + +_author_='wangjianfeng' + +from multiprocessing import Process,Pool +import os,time,random,subprocess + +'test1' \ +''' +#子进程要执行的代码 +def run_proc(name): + print('run children process %s(%s)..'%(name,os.getpid())) + +if __name__=='__main__': + print('parent process %s.'%os.getpid()) + p=Process(target=run_proc,args=('test',)) + print('children process will start!') + p.start() + p.join() + print('children process end!') + +def long_time_task(name): + print('run task %s(%s)...'%(name,os.getpid())) + start=time.time() + time.sleep(random.random()*3) + end=time.time() + print('task %s run %0.2f seconds'%(name,(end-start))) + +if __name__=='__main__': + print('parent process %s'%os.getpid()) + p=Pool(4) + for i in range(5): + p.apply_async(long_time_task,args=(i,)) + print('waiting for all subprocesses done...') + p.close() + p.join() + print('all subprocesses done') +''' +print('$ nslookup www.python.org') +r=subprocess.call(['nslookup',' www.python.org']) +print('exit code:',r) \ No newline at end of file diff --git a/Multithreading.py b/Multithreading.py new file mode 100644 index 0000000..abba093 --- /dev/null +++ b/Multithreading.py @@ -0,0 +1,162 @@ +# import _thread +import threading +from time import ctime,sleep + +##base test +# def loop0(): +# print('start loop0 at ',ctime()) +# sleep(4) +# print('loop0 done at ',ctime()) +# def loop1(): +# print('start loop1 at ',ctime()) +# sleep(2) +# print('loop0 done at ',ctime()) +# def main(): +# print('starting at ',ctime()) +# _thread.start_new_thread(loop0(),()) +# _thread.start_new_thread(loop1(),()) +# # loop0() +# # loop1() +# sleep(6) +# print('all done at ',ctime()) +# if __name__=='__main__': +# main() + +#threading +# loops=[4,2] +# def loop(nloop,nesc): +# print('start loop at ',ctime()) +# sleep(nesc) +# print('loop',nloop,'done at',ctime()) +# +# def main(): +# print('starting at:', ctime()) +# threads = [] +# nloops = range(len(loops)) +# for i in nloops: +# t=threading.Thread(target=loop,args=(i,loops[i])) +# threads.append(t) +# for i in nloops: #start threads +# threads[i].start() +# for i in nloops: #wait for all +# threads[i].join() #threads finish +# print('all done at ',ctime()) +# if __name__=='__main__': +# main() + +#threading class more object-oriented +# loops=[4,2] +# class ThreadFunc(object): +# def __init__(self,func,args,name=''): +# self.name=name +# self.func=func +# self.args=args +# def __call__(self): +# self.func(*self.args) +# def loop(nloop,nesc): +# print('start loop at ',ctime()) +# sleep(nesc) +# print('loop',nloop,'done at',ctime()) +# +# def main(): +# print('starting at:', ctime()) +# threads = [] +# nloops = range(len(loops)) +# for i in nloops: +# t=threading.Thread( +# target=ThreadFunc(loop,(i,loops[i]),loop.__name__)) +# threads.append(t) +# for i in nloops: #start threads +# threads[i].start() +# for i in nloops: #wait for all +# threads[i].join() #threads finish +# print('all done at ',ctime()) +# if __name__=='__main__': +# main() + + +#threading subclass +# loops=(4,2) +# class MyThread(threading.Thread): +# def __init__(self,func,args,name=''): +# threading.Thread.__init__(self) +# self.name=name +# self.func=func +# self.args=args +# def getResult(self): +# return self.res +# def run(self): +# print('starting',self.name,'at',ctime()) +# self.res=self.func(*self.args) +# print(self.name,'finish at',ctime()) +# def loop(nloop,nesc): +# print('start loop at ',ctime()) +# sleep(nesc) +# print('loop',nloop,'done at',ctime()) +# +# def main(): +# print('starting at:', ctime()) +# threads = [] +# nloops = range(len(loops)) +# for i in nloops: +# t=MyThread(loop,(i,loops[i]),loop.__name__) +# threads.append(t) +# for i in nloops: #start threads +# threads[i].start() +# for i in nloops: #wait for all +# threads[i].join() #threads finish +# print('all done at ',ctime()) +# if __name__=='__main__': +# main() +# +#compare single and multithreading +class MyThread(threading.Thread): + def __init__(self,func,args,name=''): + threading.Thread.__init__(self) + self.name=name + self.func=func + self.args=args + def getResult(self): + return self.res + def run(self): + print('starting',self.name,'at',ctime()) + self.res=self.func(*self.args) + print(self.name,'finish at',ctime()) + +def fib(x): + sleep(0.005) + if x<2:return 1 + return (fib(x-2)+fib(x-1)) +def fac(x): + sleep(0.1) + if x<2:return 1 + return (x*fac(x-1)) +def sum(x): + sleep(0.1) + if x<2:return 1 + return (x+sum(x-1)) + +funcs=[fib,fac,sum] +n=12 + +def main(): + nfunc=range(len(funcs)) + print('---------single thread') + for i in nfunc: + print('starting',funcs[i].__name__,'at',ctime()) + print(funcs[i](n),'what fuck') + print(funcs[i].__name__,'finish at ',ctime()) + print('\n*****multiple threads') + threads=[] + for i in nfunc: + t=MyThread(funcs[i],(n,),funcs[i].__name__) + threads.append(t) + for i in nfunc: + threads[i].start() + for i in nfunc: + threads[i].join() + print(threads[i].getResult()) + print('all done') + +if __name__ == '__main__': + main() \ No newline at end of file diff --git a/Process communication.py b/Process communication.py new file mode 100644 index 0000000..93941a1 --- /dev/null +++ b/Process communication.py @@ -0,0 +1,38 @@ +#!usr/bin/env python3 +# -*- coding: utf-8 -*- + +'process communication' + +_author_='wangjianfeng' + +from multiprocessing import Process,Queue +import os,time,random + +#写数据进程代码 +def write(q): + print('process to write :%s'%os.getpid()) + for value in ['A','B','C']: + print('put %s to queue...'%value) + q.put(value) + time.sleep(random.random()) + +#读取数据进程执行的代码 +def read(q): + print('process to read :%s'%os.getpid()) + while True: + value=q.get(True) + print('get %s from queue.'%value) + +if __name__=='__main__': + #父进程创建Queue,并且传给各个子进程?: + q=Queue() + pw=Process(target=write,args=(q,)) + pr=Process(target=read,args=(q,)) + #启动pw子进程,写入 + pw.start() + #启动PR子进程,读取 + pr.start() + #等待PW结束 + pw.join() + #pr是死循环,无法等待期结束,只能强行结束 + pr.terminate() \ No newline at end of file diff --git a/README.md b/README.md new file mode 100644 index 0000000..849602d --- /dev/null +++ b/README.md @@ -0,0 +1,5 @@ +# python_study + +平时没事了,看看第三方包玩玩代码,随意看看 + +just play diff --git a/Reptitle.py b/Reptitle.py new file mode 100644 index 0000000..28051bb --- /dev/null +++ b/Reptitle.py @@ -0,0 +1,48 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- + +' 爬虫 ' + +_author_='挖数' + +#作者:挖数 +#链接:https://www.zhihu.com/question/20899988/answer/96904827 +#来源:知乎 +#著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。 + +import requests +import urllib +import re +import random +from time import sleep +def main(): + url='https://www.zhihu.com/question/22591304/followers' + #感觉这个话题下面美女多 + headers={'省略'} + i=1 + for x in range(20,3600,20): + data={'start':'0','offset':str(x),'_xsrf':'a128464ef225a69348cef94c38f4e428'} + #知乎用offset控制加载的个数,每次响应加载20 + content=requests.post(url,headers=headers,data=data,timeout=10).text + #用post提交form data + imgs=re.findall('>>>>') + if points is None: + points=[] + while numbers>0: + point=random.randrange(1,7) + points.append(point) + numbers=numbers-1 + return points +def roll_result(total): + isBig=11<=total<=18 + isSmall=3<=total<=10 + if isBig: + return 'Big' + elif isSmall: + return 'Small' +def start_game(): + print('<<<<>>>>') + choice=['Big','Small'] + your_choice=input('Small or Big:') + if your_choice in choice: + points=roll_dice() + total=sum(points) + youwin=your_choice==roll_result(total) + if youwin: + print('The points are',points,'You Win!') + else: + print('The points are',points,'You Lose!') + else: + print('invalid input!') + start_game() +start_game() + + diff --git a/Rugular expression.py b/Rugular expression.py new file mode 100644 index 0000000..f882386 --- /dev/null +++ b/Rugular expression.py @@ -0,0 +1,28 @@ +#!usr/bin/env python3 +# -*- coding: utf-8 -*- + +'rugular expression' + +_author_='wangjianfeng' + +import re + +#匹配成功则返回一个match 否则NONE +print(re.match(r'^\d{3}-\d{3,8}','010-12345')) +print(re.match(r'^\d{3}-\d{3,8}','010 12345')) + +#切分字符 +#以空格为切分单元 +print('a b c'.split(' ')) +print(re.split(r'\s+','a b c d')) +print(re.split(r'[\s\,]+','a,b, c d')) +print(re.split(r'[\s\,\;]+','a,b ;;c d')) +m=re.match(r'^(\d{3})-(\d{3,8})$','010-123456') +print(m.group(0)) +print(m.group(1)) +print(m.group(2)) +t='19:20:55' +s=re.match(r'(0[0-9]|1[0-9]|2[0-3]|[0-9])\:(0[0-9]|1[0-9]|2[0-9]|3[0-9]|4[0-9]|5[0-9]|[0-9])\:(0[0-9]|1[0-9]|2[0-9]|3[0-9]|4[0-9]|5[0-9]|[0-9])$',t) +print(s.group()) +#贪婪匹配 +print(re.match(r'^(\d+?)(0*)$','102000').group()) \ No newline at end of file diff --git a/Serialization.py b/Serialization.py new file mode 100644 index 0000000..b43db51 --- /dev/null +++ b/Serialization.py @@ -0,0 +1,30 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- + +'serialization' + +_author_='wangjianfeng' + +import pickle +import json +#获取file-like object 的对象 +d=dict(name='bob',age=20,score=80) +print(pickle.dumps(d)) +#json之间的转换,json的标准编码是utf-8 +print(json.dumps(d)) + +#高级转化 +class Student(object): + def __init__(self,name,age,score): + self.name=name + self.age=age + self.score=score +s=Student('Bob',20,88) +#无法直接转化,采用特殊办法 +def Student2dict(std): + return{ + 'name':std.name, + 'age':std.age, + 'score':std.score + } +print(json.dumps(s,default=lambda obj:obj.__dict__)) \ No newline at end of file diff --git a/Slices.py b/Slices.py new file mode 100644 index 0000000..925bf0e --- /dev/null +++ b/Slices.py @@ -0,0 +1,22 @@ +# -*- coding: utf-8 -*- +""" +Created on Fri Jun 10 12:52:51 2016 + +@author: wangjianfeng +""" +#Slices +L=['WANGJIANFENG','LIXUEYUAN','YANXIAOHE','JACK'] +print(L[0:3])#0 to 3(not include 4 ) +print(L[0:4:2])#0 to 4 space 2 +print(L[-2:]) + +R=list(range(100)) +print(R) +print(R[::2])#100内的偶数 +print(R[:10]) +print(R[::5]) +print(R[:]) + +#also tuple and string can do it +print((1,2,3,6,5,4,9)[:3]) +print('abcdef'[:3]) \ No newline at end of file diff --git a/Struct.py b/Struct.py new file mode 100644 index 0000000..92ebcd1 --- /dev/null +++ b/Struct.py @@ -0,0 +1,35 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- + +'struct' + +_author_='wangjianfeng' + +import struct + +#>表示字节顺序是big-endian,也就是网络序,I表示4字节无符号整数。 +print(struct.pack('>I',10240099)) +print(struct.unpack('IH',b'\xf0\xf0\xf0\xf0\x80\x80')) + +#Bmp read +def check_file(file_path): + try: + #with open(file_path,'rb') as f: + #s=f.read(30) + s=open(file_path,'rb').read(30) + info=struct.unpack('?@[\]^_`{|}~ +import string +path='E:\\Walden.txt' +with open(path,'r',encoding='utf-8') as text: + #在文字首位去掉了连在一起的标点符号,并把字母大写的单词转换为小写 + words=[raw_word.strip(string.punctuation).lower() for raw_word in text.read().split()] + #将列表用set函数转换为集合,自动去掉了其中的所有重复元素 + word_index=set(words) + #创建了一个以单词为键(key)出现频率为值(value)的字典 + counts_dict={index:words.count(index) for index in word_index} + #打印整理后的函数,其中key=lambda x: count_dict[x]为lambda表达式,匿名函数 +for word in sorted(counts_dict,key=lambda x: counts_dict[x],reverse=True): + print('{}--{} times'.format(word,counts_dict[word])) \ No newline at end of file diff --git a/XML-weather.py b/XML-weather.py new file mode 100644 index 0000000..d21a42f --- /dev/null +++ b/XML-weather.py @@ -0,0 +1,89 @@ +#!usr/bin/env python3 +# -*- coding: utf-8 -*- + +'xml weather' + +_author_='wangjianfeng' + +from xml.parsers.expat import ParserCreate +from collections import OrderedDict + +class WeatherSaxHandler(object): + days=('today','tomorrow') + def __init__(self): + self.weather=OrderedDict()#define sequence Dict + self.day=0 #1 is today ,2 is tomorrow,3 is other day + def start_element(self,name,attrs): + if name=='yweather:location': + self.weather['city']=attrs['city'] + self.weather['country']=attrs['country'] + elif name=='yweather:forecast': + if self.day<2:#today + self.weather[WeatherSaxHandler.days[self.day]]={} + self.weather[WeatherSaxHandler.days[self.day]]['text']=attrs['text'] + self.weather[WeatherSaxHandler.days[self.day]]['low']=int(attrs['low']) + self.weather[WeatherSaxHandler.days[self.day]]['high']=int(attrs['high']) + self.day+=1 + def end_element(self,name):pass + def char_data(self,data):pass + +def parse_weather(xml): + parser=ParserCreate() + handler=WeatherSaxHandler() + parser.StartElementHandler=handler.start_element + parser.EndElementHandler=handler.end_element + parser.CharacterDataHandler=handler.char_data + parser.Parse(xml) + return handler.weather + + +def parser_weather(xml): + return { + 'city':'Beijing', + 'Country':'CHINA', + 'today':{ + 'text':'Partly Cloudy', + 'low':20, + 'high':33 + }, + 'tomorrow':{ + 'text':'Sunny', + 'low':21, + 'high':34 + } + } +#test +data = r''' + + + Yahoo! Weather - Beijing, CN + Wed, 27 May 2015 11:00 am CST + + + + + + + 39.91 + 116.39 + Wed, 27 May 2015 11:00 am CST + + + + + + + + + +''' +weather = parse_weather(data) +assert weather['city'] == 'Beijing', weather['city'] +assert weather['country'] == 'China', weather['country'] +assert weather['today']['text'] == 'Partly Cloudy', weather['today']['text'] +assert weather['today']['low'] == 20, weather['today']['low'] +assert weather['today']['high'] == 33, weather['today']['high'] +assert weather['tomorrow']['text'] == 'Sunny', weather['tomorrow']['text'] +assert weather['tomorrow']['low'] == 21, weather['tomorrow']['low'] +assert weather['tomorrow']['high'] == 34, weather['tomorrow']['high'] +print('Weather:', str(weather)) \ No newline at end of file diff --git a/XML.py b/XML.py new file mode 100644 index 0000000..1e65810 --- /dev/null +++ b/XML.py @@ -0,0 +1,35 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- + +'XML' + +_author_='wangjianfeng' + +#操作XML,have two way:DOM VS SAX,DOM will read whole into memory,resolved to a tree;SAX is flow pattern, +from xml.parsers.expat import ParserCreate + +class DafaultSaxHandler(object): + def start_element(self,name,attrs): + print('sax:start_element:{},attrs:{}'.format(name,str(attrs))) + + def end_element(self,name): + print('sax:end_element:{}'.format(name)) + + def char_data(self,text): + if self.char_data==None: + pass + else: + print('sax:char_data:{}'.format(text)) + +xml = r''' +
    +
  1. Python
  2. +
  3. Ruby
  4. +
+''' +handler=DafaultSaxHandler() +parser=ParserCreate() +parser.StartElementHandler=handler.start_element +parser.EndElementHandler=handler.end_element +parser.CharacterDataHandler=handler.char_data +parser.Parse(xml) \ No newline at end of file diff --git a/Yanghui Triangles.py b/Yanghui Triangles.py new file mode 100644 index 0000000..efb000b --- /dev/null +++ b/Yanghui Triangles.py @@ -0,0 +1,20 @@ +#!usr/bin/env python3 +# -*- coding: utf-8 -*- + +_author_='wangjianfeng' + +' Yanghui triangle or Pascal trangle' + +def triangles(): + N=[1] + while True: + yield N + N.append(0) + N=[N[i-1]+N[i] for i in range(len(N))] +n=0 +for t in triangles(): + print(t) + n=n+1 + if n==10: + break + \ No newline at end of file diff --git a/abstest.py b/abstest.py new file mode 100644 index 0000000..e46f7ba --- /dev/null +++ b/abstest.py @@ -0,0 +1,13 @@ +# -*- coding: utf-8 -*- +""" +Spyder Editor + +This is a temporary script file. +""" +def my_abs(x): + if not isinstance(x,(int,float)): + raise TypeError('bad operand type') + if x>=0: + return x + else: + return -x diff --git a/account_login.py b/account_login.py new file mode 100644 index 0000000..f78bf74 --- /dev/null +++ b/account_login.py @@ -0,0 +1,30 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- + +'account login' + +_author_='wangjianfeng' + +password_list=['****','12345'] + +def account_login(): + tries=3 + while tries>0: + password=input('please input your password:') + password_correct=password==password_list[-1] + password_reset=password==password_list[0] + if password_correct: + print('login success!') + elif password_reset: + new_password=input('enter your new password:') + password_list.append(new_password) + print('change your password successfully!') + account_login() + else: + print('wrong password or invalid input!') + tries=tries-1 + print(tries,'time left') + else: + print('your account has been suspended') +account_login() + \ No newline at end of file diff --git a/base64.py b/base64.py new file mode 100644 index 0000000..b8c66fc --- /dev/null +++ b/base64.py @@ -0,0 +1,24 @@ +#!usr/bin/env python3 +# -*- coding: utf-8 -*- + +'base64 ' + +_author_='wangjianfeng' + +#base64是一种用64种字符来表示二进制数据的方法 +import base64 +print(base64.b64encode(b'binary\x00string')) +print(base64.b64decode(b'YmluYXJ5AHN0cmluZw==')) +#base64中有+ /在url中不能作为参数,所以又有一种urlsafe的base64编码,其实是+ /变为了-_ +print(base64.b64encode(b'i\xb7\x1d\xfb\xef\xff')) +print(base64.urlsafe_b64encode(b'i\xb7\x1d\xfb\xef\xff')) +print(base64.urlsafe_b64decode('abcd--__')) +#在url、cookies中=会造成很多歧义,所以很多base64编码会把=去掉 +def safe_base64_decode(s): + return base64.b64decode(s+b'='*(len(s)%4)) + +# 测试: +assert b'abcd' == safe_base64_decode(b'YWJjZA=='), safe_base64_decode('YWJjZA==') +assert b'abcd' == safe_base64_decode(b'YWJjZA'), safe_base64_decode('YWJjZA') +print('Pass') + diff --git a/christmas tree.py b/christmas tree.py new file mode 100644 index 0000000..b6f8253 --- /dev/null +++ b/christmas tree.py @@ -0,0 +1,8 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- + +'christmas tree' + +_author_='wangjianfeng' + +print(' *',' * *','* * *',' |',sep='\n') \ No newline at end of file diff --git a/do iter.py b/do iter.py new file mode 100644 index 0000000..e087e9c --- /dev/null +++ b/do iter.py @@ -0,0 +1,20 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- + +' do iter ' + +_author_='wangjianfeng' + +#check which can do +from collections import Iterable +print('Iterabel?\'abc\':',isinstance('abc',Iterable))# string can or not +print('Iterable?[1,2,3]',isinstance([1,2,3],Iterable))# list can or not +print('Iterable?123',isinstance(123,Iterable))# integer can or not + +#类似JAVA中下标循环,采用python中内置的一个function-enumerate +for i,value in enumerate(['a','b','c']): + print(i,value) + +#two variables in the loop +for x,y in [(1,2),(3,4),(5,6)]: + print(x,y) \ No newline at end of file diff --git a/high-order function.py b/high-order function.py new file mode 100644 index 0000000..20e982b --- /dev/null +++ b/high-order function.py @@ -0,0 +1,12 @@ +#!usr/bin/env python3 +# -*- coding:utf-8 -*- + +' high-order function ' + +_author_='wangjianfeng' + +def add(a,b,f): + return f(a)+f(b) +a,b=-5,6 +f=abs +print(add(a,b,f)) \ No newline at end of file diff --git a/in and out.py b/in and out.py new file mode 100644 index 0000000..4fbc1ff --- /dev/null +++ b/in and out.py @@ -0,0 +1,12 @@ +# -*- coding: utf-8 -*- +""" +Spyder Editor + +This is a temporary script file. +""" +surname=input('input your surname:') +print('\n') +firstname=input('input your firstname:') +print('your surnmae is:',surname) +print(surname) +print('your firstname is:',firstname) diff --git a/keyword parameter.py b/keyword parameter.py new file mode 100644 index 0000000..565653f --- /dev/null +++ b/keyword parameter.py @@ -0,0 +1,19 @@ +# -*- coding: utf-8 -*- +""" +Created on Wed Jun 8 10:49:47 2016 + +@author: wangjianfeng2014 +""" +#keyword parameter +def person(name,age,**kw): + print('name:',name,'age:',age,'other:',kw) +person('wangjianfeng',26) +person('lixueyuan',25,city='xian') +extra={'city':'Beijing','job':'engineer'} +person('yanxiaohe',100,city=extra['city'],job=extra['job']) +person('yanxiaohe',100,**extra) +#named keyword parameters +def people(name,age,*,city,job): + print(name,age,city,job) +people('jack',24,city='beijing',job='engineer') + diff --git a/list comprehensions.py b/list comprehensions.py new file mode 100644 index 0000000..36078a8 --- /dev/null +++ b/list comprehensions.py @@ -0,0 +1,27 @@ +#usr/bin/env python3 +# -*- coding:utf-8 -*- + +#list comprehensions +print(list(range(10))) +#1*1,2*2,3*3,4*4..... +print([x*x for x in range(1,11)]) + +#并且后面可以加上一些判断来筛选所需要的内容 +print([x*x for x in range(1,11) if x%2==0]) + +#doulbe layer cycle +print([m+n for m in 'ABC' for n in 'yxt']) + +#在dict中items()同时可以迭代key和value +d={'x':'A','y':'B','z':'C'} +for k,v in d.items(): + print(k,'=',v) +print([k+'='+v for k,v in d.items()]) + +#大写变小写 +L=['HELLO','World','IBM','Apple'] +print([s.lower() for s in L]) + +#test +R=['Hello','World',18,'IBM','Apple',None] +print([s.lower() for s in L if isinstance(s,str)]) \ No newline at end of file diff --git a/list generator.py b/list generator.py new file mode 100644 index 0000000..2c7bb4e --- /dev/null +++ b/list generator.py @@ -0,0 +1,22 @@ +#!usr/bin/env python3 +# -*- coding: utf-8 -*- + +' list generator ' + +_author_='wangjianfeng' + +#the difference between generator and comprehensions +print([x*x for x in range(10)]) +g=(x*x for x in range(10)) +for n in g: + print(n) +#Fibonacci sequence +def fib(max): + n,a,b=0,0,1 + while n>>>>>> origin/Base diff --git a/multiplication table.py b/multiplication table.py new file mode 100644 index 0000000..59f70fe --- /dev/null +++ b/multiplication table.py @@ -0,0 +1,12 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- + +'99 multiplication table' + +_author_='wangjianfeng' + +for i in range(1,10): + for j in range(1,i+1): + #print('%d*%d=%d\t'%(j,i,i*j),end='') + print('{}*{}={}\t'.format(j,i,i*j),end='') + print('') diff --git a/network_program/socket/tcp_cli_ts.py b/network_program/socket/tcp_cli_ts.py new file mode 100644 index 0000000..903ca85 --- /dev/null +++ b/network_program/socket/tcp_cli_ts.py @@ -0,0 +1,22 @@ +#!usr/bin/env python3 +# -*- coding: utf-8 -*- + +from socket import * + +HOST = "localhost" +PORT = 21567 +BUFSIZ = 1024 +ADDR = (HOST, PORT) + +while True: + tcpclisock = socket(AF_INET, SOCK_STREAM) + tcpclisock.connect(ADDR) + data = input("> ") + if not data: + break + tcpclisock.send("{} \n".format(data).encode("utf-8")) + rec = tcpclisock.recv(BUFSIZ) + if not rec: + break + print(rec.decode("utf-8")) + tcpclisock.close() diff --git a/network_program/socket/tcp_s_ts.py b/network_program/socket/tcp_s_ts.py new file mode 100644 index 0000000..d95d911 --- /dev/null +++ b/network_program/socket/tcp_s_ts.py @@ -0,0 +1,28 @@ +#!usr/bin/env python3 +# -*- coding: utf-8 -*- + +from socket import * +from time import ctime + +HOST = "" +PORT = 21567 +BUFSIZ = 1024 +ADDR = (HOST, PORT) + +tcpsersock = socket(AF_INET, SOCK_STREAM) +tcpsersock.bind(ADDR) +tcpsersock.listen(5) + +while True: + print("waiting for connection....") + tcpclisock, addr = tcpsersock.accept() + print("...connected from {}".format(addr)) + + while True: + data = tcpclisock.recv(BUFSIZ) + if not data: + break + tcpclisock.send("[{}] {}".format(ctime(), data).encode("utf-8")) + tcpclisock.close() + +tcpsersock.close() # that is important diff --git a/network_program/socket/tcp_ss_ts.py b/network_program/socket/tcp_ss_ts.py new file mode 100644 index 0000000..8f7ba85 --- /dev/null +++ b/network_program/socket/tcp_ss_ts.py @@ -0,0 +1,20 @@ +#!usr/bin/env python3 + +from socketserver import (TCPServer as TCP, StreamRequestHandler as SRH) +from time import ctime + +HOST = "" +PORT = 21567 +BUFSIZ = 1024 +ADDR = (HOST, PORT) + + +class MyRequestHandler(SRH): + def handle(self): + print("...connected from {}".format(self.client_address)) + self.wfile.write("[{}] {}".format(ctime(), self.rfile.readline()).encode("utf-8")) + + +tcpsersock = TCP(ADDR, MyRequestHandler) +print("waiting for connection.....") +tcpsersock.serve_forever() diff --git a/network_program/socket/udp_cli_ts.py b/network_program/socket/udp_cli_ts.py new file mode 100644 index 0000000..18d5ced --- /dev/null +++ b/network_program/socket/udp_cli_ts.py @@ -0,0 +1,22 @@ +#!usr/bin/env python3 +# -*- coding: utf-8 -*- + +from socket import * + +HOST = "127.0.0.1" +PORT = 21567 +BUFSIZ = 1024 +ADDR = (HOST, PORT) + +udpclisock = socket(AF_INET, SOCK_DGRAM) + +while True: + data = input("> ") + if not data: + break + udpclisock.sendto(data.encode(), ADDR) + data, addr = udpclisock.recvfrom(BUFSIZ) + if not data: + break + print(data) +udpclisock.close() \ No newline at end of file diff --git a/network_program/socket/udp_s_ts.py b/network_program/socket/udp_s_ts.py new file mode 100644 index 0000000..91a9f94 --- /dev/null +++ b/network_program/socket/udp_s_ts.py @@ -0,0 +1,20 @@ +#!usr/bin/env python3 + +from socket import * +from time import ctime + +HOST = "" +PORT = 21567 +BUFSIZ = 1024 +ADDR = (HOST, PORT) + +udpsersock = socket(AF_INET, SOCK_DGRAM) +udpsersock.bind(ADDR) + +while True: + print("waiting for message....") + data, addr = udpsersock.recvfrom(BUFSIZ) + udpsersock.sendto("[{}] {}".format(ctime(), data).encode(), addr) + print(".....received from and return to : {}".format(addr)) + +udpsersock.close() diff --git a/network_program/twisted/tcp_cli_tw.py b/network_program/twisted/tcp_cli_tw.py new file mode 100644 index 0000000..39bf9ec --- /dev/null +++ b/network_program/twisted/tcp_cli_tw.py @@ -0,0 +1,31 @@ +#!usr/bin/env python3 + +from twisted.internet import protocol, reactor + +HOST = "127.0.0.1" +PORT = 21567 + + +class TcpcliProtocol(protocol.Protocol): + def sendata(self): + data = input("> ") + if data: + print("sending .....{}".format(data)) + self.transport.write(data.encode()) + else: + self.transport.loseConnection() + + def connectionMade(self): + self.sendata() + + def dataReceived(self, data): + print(data) + self.sendata() + + +class TcpcliFactory(protocol.ClientFactory): + protocol = TcpcliProtocol + clientConnectionLost = clientConnectionFailed = lambda self, connector, reason: reactor.stop() + +reactor.connectTCP(HOST, PORT, TcpcliFactory()) +reactor.run() \ No newline at end of file diff --git a/network_program/twisted/tcp_s_tw.py b/network_program/twisted/tcp_s_tw.py new file mode 100644 index 0000000..bde5288 --- /dev/null +++ b/network_program/twisted/tcp_s_tw.py @@ -0,0 +1,23 @@ +#!usr/bin/env python3 + +from twisted.internet import protocol, reactor +from time import ctime + +PORT = 21567 + + +class TcpserProtocol(protocol.Protocol): + def connectionMade(self): + clnt = self.clnt = self.transport.getPeer().host + print(clnt) + print("....connected from {}".format(clnt)) + + def dataReceived(self, data): + self.transport.write("[{}] {}".format(ctime(), data).encode()) + + +factory = protocol.Factory() +factory.protocol = TcpserProtocol +print("....waiting for connection ....") +reactor.listenTCP(PORT, factory) +reactor.run() diff --git a/parameter combination.py b/parameter combination.py new file mode 100644 index 0000000..3ca52d3 --- /dev/null +++ b/parameter combination.py @@ -0,0 +1,20 @@ +# -*- coding: utf-8 -*- +""" +Created on Wed Jun 8 13:56:51 2016 + +@author: wangjianfeng2014 +""" +#parameter combination +def f1(a,b,c=0,*args,**kw): + print('a=',a,'b=',b,'c=',c,'args=',args,'kw=',kw) +def f2(a,b,c=0,*,d,**kw): + print('a=',a,'b=',b,'d=',d,'kw',kw) +f1(1,2) +f1(1,2,3) +f1(1,2,3,'a','b') +f1(1,2,3,'a','b',x=99) +f2(1,2,d=99,ext=None) +#use list or tuple +args=(1,2,3,4) +kw={'d':99,'m':'#'} +f1(*args,**kw) \ No newline at end of file diff --git a/quadratic equation with one unknown.py b/quadratic equation with one unknown.py new file mode 100644 index 0000000..f92f73e --- /dev/null +++ b/quadratic equation with one unknown.py @@ -0,0 +1,20 @@ +# -*- coding: utf-8 -*- +""" +Created on Tue Jun 7 10:08:05 2016 + +@author: wangjianfeng2014 +""" + +import math + +def quadratic(a,b,c): + m=b*b-4*a*c + if a==0: + return -c/b + elif m<0: + return 'no answer!' + else: + return (-b-math.sqrt(m))/2/a,(-b+math.sqrt(m))/2/a +x1=quadratic(2,3,1) +print(x1) + diff --git a/recursive function.py b/recursive function.py new file mode 100644 index 0000000..8f10c4b --- /dev/null +++ b/recursive function.py @@ -0,0 +1,23 @@ +# -*- coding: utf-8 -*- +""" +Created on Wed Jun 8 14:31:21 2016 + +@author: wangjianfeng2014 +""" +#recursive function +''' +def fact(n): + if(n==1): + return 1 + return n*fact(n-1) +print(fact(1)) +print(fact(1000)) +''' +#tail recursion(but when n=1000 it is also stack overflow,that is too bad!) +def fact(n): + return fact_iter(n,1) +def fact_iter(num,product): + if num==1: + return product + return fact_iter(num-1,num*product) +print(fact(100)) \ No newline at end of file diff --git a/sorted.py b/sorted.py new file mode 100644 index 0000000..e81aa5a --- /dev/null +++ b/sorted.py @@ -0,0 +1,21 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- + +' sorted ' + +_author_='wangjianfeng' + +#use sorted() to sort list +print(sorted([1,5,68,8,7,96,3,6,9,8,4])) + +#also sorted() is a high-order function +print(sorted([36,-9,-845,52,45,-875],key=abs)) + +#sorted str compare ASCII +print(sorted(['bob', 'about', 'Zoo', 'Credit'])) +print(sorted(['bob','about','Zoo','Credit'],key=str.lower)) + +#practice +L=[('Bob',75),('Adam',92),('Bart',66),('Lisa',88)] +print(sorted(L,key=lambda t:t[0])) +print(sorted(L,key=lambda t:t[1],reverse=True)) diff --git a/students registers.py b/students registers.py new file mode 100644 index 0000000..dd3c099 --- /dev/null +++ b/students registers.py @@ -0,0 +1,15 @@ +# -*- coding: utf-8 -*- +""" +Created on Wed Jun 8 10:01:28 2016 + +@author: wangjianfeng2014 +""" +#students registers +def enroll(name,gender,age=6,city='Beijing'): + print('name:%s,gender:%s,age:%d,city:%s'%(name,gender,age,city)) + #print('name',name) + #print('gender',gender) + #print('age',age) + #print('city',city) + +enroll('wangjianfeng','M') \ No newline at end of file diff --git a/test.py b/test.py new file mode 100644 index 0000000..a5856d4 --- /dev/null +++ b/test.py @@ -0,0 +1,14 @@ + + +' test ' + +_author_='wangjianfeng' + + +import requests + +# url='http://http://pythonscraping.com/files/processing.php' +# params={'firstname':'wang','lastname':'jianfeng'} +# r=requests.post("http://pythonscraping.com/pages/files/processing.php",data=params) +a=1+2 +print(a) \ No newline at end of file diff --git a/text open and write.py b/text open and write.py new file mode 100644 index 0000000..89d3123 --- /dev/null +++ b/text open and write.py @@ -0,0 +1,31 @@ +#!/usr/bin/env python3 +# -*- coding:utf-8 -*- + +'file open write close filter' + +_author_='wangjianfeng' + +def text_create(name,msg): + desktop_path='C:\\Users\wangjianfeng2014\Desktop\\' + full_path=desktop_path+name+'.txt' + file=open(full_path,'w') + file.write(msg) + file.close + print('done') +def text_filter(word,censored_word='lame',changed_word='awesome'): + return word.replace(censored_word,changed_word) +def censored_text_create(name,msg): + clean_msg=text_filter(msg) + text_create(name,clean_msg) +censored_text_create('my file','python is lame') + +#每次打开读写都需要open和close 太繁琐,我们使用with +with open('C:\\Users\wangjianfeng2014\Desktop\my file.txt','r',encoding='gbk') as f: + print(f.read())#如果文件太多可以考虑用read(size) or readlines() + +#读取图片格式文件使用 rb +f=open('C:\\Users\wangjianfeng2014\Desktop\\54877586241642729.jpg','rb') +f.read() +#字符编码以及一些忽略错误 +with open('C:\\Users\wangjianfeng2014\Desktop\my file.txt','r',encoding='gbk',errors='ignore') as f: + print(f.read()) \ No newline at end of file diff --git a/text.txt b/text.txt new file mode 100644 index 0000000..6863f66 --- /dev/null +++ b/text.txt @@ -0,0 +1,16 @@ + + + 极客学院爬虫测试 + + + + + \ No newline at end of file diff --git a/tower of hanoi.py b/tower of hanoi.py new file mode 100644 index 0000000..8a69fd8 --- /dev/null +++ b/tower of hanoi.py @@ -0,0 +1,15 @@ +# -*- coding: utf-8 -*- +""" +Created on Wed Jun 8 15:24:26 2016 + +@author: wangjianfeng2014 +""" +#tower of hanoi(use recursion function) +def move(n,a,b,c): + if n==1: + print('move',a,'-->',c) + return + move(n-1,a,c,b) + print('move',a,'-->',c) + move(n-1,b,a,c) +move(12,'A','B','C') \ No newline at end of file diff --git a/variable parameters.py b/variable parameters.py new file mode 100644 index 0000000..1ba291f --- /dev/null +++ b/variable parameters.py @@ -0,0 +1,23 @@ +# -*- coding: utf-8 -*- +""" +Created on Wed Jun 8 10:38:08 2016 + +@author: wangjianfeng2014 +""" +#variable parameters(only a *,but refuse a list or tuple) +def calc(*numbers): + sum=0 + for n in numbers: + sum=sum+n*n + return sum +'''' +r=calc([1,2,3]) +print(r) +r=calc([1,2,3,5]) +print(r) +''' +r=calc(1,2) +print(r) +#to slove list or tuple questions +nums=[1,2,3,5] +print(calc(*nums)) \ No newline at end of file