实践中学Python3

    xiaoxiao2021-03-25  120

    更多PYTHON交流移步BLOG,交流插件需要FQ 初学实践代码 https://github.com/vonsago/Python3_study_note.git 简单爬虫: https://github.com/vonsago/spider_miui.git 偶发一个有趣的网站: http://www.pythonchallenge.com/

    Queston 1:

    #!/usr/bin/python3

    的作用

    这一行叫做 hash-bang,它定义了解释器所在的位置 它可能是一个bash,ruby,perl或任何其他脚本语言的解释器。 如在脚本上设置此行可以直接运行./script.py。 除非你运行python3 script.py或设置hash-bang行,否则操作系统不知道它是一个python脚本。

    使用/usr/bin/env python3可移植到不同的操作系统。

    Queston 2:

    # -*- coding: cp-1252 -*-

    默认情况下,Python 3 源码文件以 UTF-8 编码,所有字符串都是 unicode 字符串。 当然你也可以为源码文件指定不同的编码:

    # -*- coding: cp-1252 -*-

    Queston 3: from … import … 是什么意思 比如:

    from os.path import exists from random import randrange ,choice

    大致的作用就是加载模块os.path,但是只取后面exists加入到当前命名空间

    作用就是为了方便写代码: 比如我要访问django.contrib.auth.models.User,这太长了 from os.path import exists 就允许你直接使用函数:exists() 而不用写前面的。 如果想从os.path导入多个变量或函数,可以os.path import foo,bar。

    另外:from os.path import *可以导入os.path所有的函数和变量,但是可能导致覆盖局部变量和函数。 比如:

    exit = 42 from sys import * //exit被覆盖 //OR from sys import * exit = 42 //sys.exit()被覆盖,不能被调用 //OR from os import * from urllib import * open(foo) //os.open还是urllib.open?所以结果,也是方法被覆盖

    “import foo”和“from foo import *”之间的区别(来自Maik Hoepfel) Queston 4: python 的数据类型: 在 Python 中,变量没有类型,我们所说的"类型"是变量所指的内存中对象的类型。 Python 中的变量不需要声明。每个变量在使用前都必须赋值,变量赋值以后该变量才会被创建。 Python3 中有六个标准的数据类型:

    1.Number(数字) 2.String(字符串) 3.List(列表) 4.Tuple(元组) 5.Sets(集合) 6.Dictionary(字典)

    Queston 5: Python3中消除字符串中特殊字符

    >>> import re >>> string='123what321' >>> print(string) 123what321 >>> re.sub('[0123456789]','',string) 'what' >>> string=re.sub('[0123456789]','x',string) >>> print(string) xxxwhatxxx

    Queston 6: assert在python3中的用法: Assert语句是将调试断言插入程序的便捷方式:

    assert '''条件'''

    Queston 7: zip在python3中的用法: Python 3中的zip函数返回一个迭代器。作用合并元素,节省内存。

    >>> x = [1, 2, 3] >>> y = [4, 5, 6] >>> zipped = zip(x, y) >>> list(zipped) [(1, 4), (2, 5), (3, 6)]

    用*拆分:

    >>> x2, y2 = zip(*zip(x, y)) >>> x == list(x2) and y == list(y2) True

    doc

    Queston 8: 生成器 在 Python 中,使用了 yield 的函数被称为生成器(generator)。 跟普通函数不同的是,生成器是一个返回迭代器的函数,只能用于迭代操作,更简单点理解生成器就是一个迭代器。 在调用生成器运行的过程中,每次遇到 yield 时函数会暂停并保存当前所有的运行信息,返回yield的值。并在下一次执行 next()方法时从当前位置继续运行。 以下实例使用 yield 实现斐波那契数列:

    #!/usr/bin/python3 import sys def fibonacci(n): # 生成器函数 - 斐波那契 a, b, counter = 0, 1, 0 while True: if (counter > n): return yield a a, b = b, a + b counter += 1 f = fibonacci(10) # f 是一个迭代器,由生成器返回生成 while True: try: print (next(f), end=" ") except StopIteration: sys.exit()

    Queston 9: 深拷贝浅拷贝

    >>>a = [1,2,['a','b']] >>>b=a //发现id(a)==id(b)==id([1,2,['a','b']]) >>> print(a) [1, 2, ['a', 'b']] >>> print(b) [1, 2, ['a', 'b']] >>> a.append('c') >>> print(a) [1, 2, ['a', 'b'], 'c'] >>> print(b) [1, 2, ['a', 'b'], 'c'] #说明可以通过对象b或者a,来更改[1,2,['a','b']]的值 #copy模块的使用 >>>import copy >>> c =copy.copy(a) >>> c [1, 2, ['a', 'b'], 'c'] >>> a.append(3) >>> a [1, 2, ['a', 'b'], 'c', 3] >>> c [1, 2, ['a', 'b'], 'c'] #前拷贝,只拷贝父对象,所以c[0],c[1],c[2]都是之前的地址 >>> a[2].append('x') >>> a [1, 2, ['a', 'b', 'x'], 'c', 3] >>> b [1, 2, ['a', 'b', 'x'], 'c', 3] >>> c [1, 2, ['a', 'b', 'x'], 'c'] #深拷贝,完全独立于父对象,d[2]和之前地址不同 >>> d = copy.deepcopy(a) >>> d [1, 2, ['a', 'b', 'x'], 'c', 3] >>> a.append(4) >>> a [1, 2, ['a', 'b', 'x'], 'c', 3, 4] >>> d [1, 2, ['a', 'b', 'x'], 'c', 3] >>> a[2].append('y') >>> a [1, 2, ['a', 'b', 'x', 'y'], 'c', 3, 4] >>> d [1, 2, ['a', 'b', 'x'], 'c', 3]

    下面图解

    Queston 9: python并发:多线程异步IO文件 代码模板:http://blog.csdn.net/qq_15015129/article/details/77485188

    Queston 10: python 网络爬虫:异步请求,解决阻塞 代码模板:http://blog.csdn.net/qq_15015129/article/details/77487768

    Queston 11: python3 实现计算器基本功能 代码:http://blog.csdn.net/qq_15015129/article/details/74992553 Queston 12: python常见编码问题 u’'类型

    a=u'\xe5\x9c\xa3\xe5\xbd\xbc\xe5\xbe\x97\xe5\xa0\xa1\xe6\x8e\x92\xe5\x90\x8d\xe7\xac\xac 1 \xe9\xa4\x90\xe5\x8e\x85 (\xe5\x85\xb1 8,650 \xe9\x97\xb4)' print a print a.encode('raw-unicode-escape')

    处理\u00类型的编码

    >>> a = u'\u00e6\u0097\u00a5\u00e6\u009c\u00ac\u00e5\u009f\u00bc\u00e7\u008e\u0089\u00e5\u00b8\u0082\n' >>> print a >>> print a.encode('iso-8859-1').decode('utf-8')

    \uxxxx解码

    a='\u56e0' print a.decode('unicode-escape')

    如果是str的过程

    a = '\u00e6\u0097\u00a5\u00e6\u009c\u00ac\u00e5\u009f\u00bc\u00e7\u008e\u0089\u00e5\u00b8\u0082' print a.decode('unicode-escape').encode('iso-8859-1').decode('utf8')

    unicode+ascii,且u前没有\

    #coding=utf8 s = 'u00e7u0088u00b1u00e5u00b0u0094u00e7u00a6u008fu00e7u0089u00b9u00e5u009fu008eu00e9u0099u0085u00e9u0085u0092u00e5u00bau0097u00e6u0098u00afu00e4u00b8u0080u00e5u00aeu00b6u00efu00bcu008cu00e8u00b7u009du00e7u00a6u00bbu00e5u00aeu0089u00e6u00a0u00bcu00e5u00b0u0094u00e5u008du009au00e7u0089u00a9u00e9u00a6u0086u00e5u0092u008cu00e5u0085u008bu00e9u009bu00b7u00e9u00bbu0098u00e6u00a1u00a5u00e4u00b8u008du00e5u0088u00b0 15 u00e5u0088u0086u00e9u0092u009fu00e7u009au0084u00e6u00adu00a5u00e8u00a1u008cu00e8u00b7u00afu00e7u00a8u008bu00e3u0080u0082u00e8u0080u008cu00e4u00b8u0094u00efu00bcu008cu00e8u00bfu0099u00e5u00aeu00b6u00e9u0085u0092u00e5u00bau0097u00e8u00b7u009du00e7u00a6u00bbu00e5u009fu0083u00e5u00b0u0094u00e7u00a6u008fu00e7u0089u00b9u00e5u00a4u00a7u00e6u0095u0099u00e5u00a0u0082u00e5u0092u008cEgapark Erfurtu00e4u00b8u008du00e5u0088u00b0 5 u00e5u0085u00acu00e9u0087u008cu00e3u0080u0082 u00e6u00adu00a4u00e9u0085u0092u00e5u00bau0097u00e6u008fu0090u00e4u00beu009bu00e9u00a4u0090u00e5u008eu0085u00e3u0080u0081u00e5u00b1u008bu00e9u00a1u00b6u00e9u009cu00b2u00e5u008fu00b0u00e5u0092u008cu00e5u00b9u00b2u00e6u00b4u0097/u00e6u00b4u0097u00e8u00a1u00a3u00e6u009cu008du00e5u008au00a1u00e3u0080u0082u00e5u00a6u0082u00e6u009eu009cu00e6u0082u00a8u00e6u0083u00b3u00e5u0096u009du00e6u009du00afu00e9u00a5u00aeu00e6u0096u0099u00e6u0094u00beu00e6u009du00beu00e4u00b8u0080u00e4u00b8u008bu00efu00bcu008cu00e9u0085u0092u00e5u0090u00a7/u00e9u0085u0092u00e5u00bbu008au00e7u00bbu009du00e5u00afu00b9u00e6u0098u00afu00e6u0082u00a8u00e7u009au0084u00e5u00a5u00bdu00e5u008eu00bbu00e5u00a4u0084u00e3u0080u0082' if __name__ == '__main__': import re pattern = re.compile(r'((u00([a-z0-9]){2})+)') for i in pattern.findall(s): s = s.replace(i[0], i[0].replace('u', '\\u').decode('unicode-escape').encode('iso-8859-1'))

    DOC:https://docs.python.org/2/howto/unicode.html

    Queston 12.5: 中文写入csv文件乱码问题(我这里针对问题12第一种类型写入csv文件的情况得到验证)

    #打开csv文件后加入如下代码 import codecs csvFile.write(codecs.BOM_UTF8)

    Queston 13: mysql数据库操作(py2.7): http://blog.csdn.net/qq_15015129/article/details/77574457

    Queston 14: list[x::y]是什么作用

    It slices list[startAt:endBefore:skip]

    Queston 15: 使用多个字符分隔字符串

    >>> import re >>> s = '123 456,789;000' >>> re.split('[ ,;]',s) ['123', '456', '789', '000'] >>>

    Queston 16: python正则,注意多行匹配加re.S http://blog.csdn.net/qq_15015129/article/details/73064813

    Queston 17: 数据库插入模板

    def insert_db(data): db = mysql_db_admin.connection() cur = db.cursor() sql = """INSERT INTO hotel_suggestions_city( city_id, source, suggestions, select_index,annotation ) VALUES (%s,%s,%s,%s,%s)""" try: cur.execute(sql,(data[0],data[1],data[2],data[3])) print '--OK--' db.commit() except Exception as e: print '--err-',e db.rollback() db.close()

    Queston 18: 读取.txt .csv等常见文件模板

    def get_datas_from_file(fname): def get_data_from_csv(fname): with open(fname) as f: final= [] f_csv = csv.reader(f) headers = next(f_csv) print headers for row in f_csv: final.append(row) return final def get_data_from_forml(fname): with open(fname) as f: final = [] datas = f.readlines() for data in datas: final.append(data.replace('\n','')) return final if fname.find('.')>0: if fname.split('.')[-1]=='csv': return get_data_from_csv(fname) else: return get_data_from_forml(fname) #将会输出一个列表

    Queston 19: Map, Filter and Reduce 1.map: 应用函数到一个列表所有元素

    map(function_to_apply, list_of_inputs) items = [1, 2, 3, 4, 5] squared = list(map(lambda x: x**2, items))

    2.filter: 过滤器能创建一个函数返回True的列表

    numbers = range(-5, 5) less = list(filter(lambda x: x < 0, numbers))

    它类似for循环,但它是一个内置函数所以跟快

    3.reduce: 可以用于一个列表计算乘积

    from functools import reduce product = reduce((lambda x, y: x * y), [1, 2, 3, 4]) # Output: 24

    Queston 20: super method 的用法 https://docs.python.org/2/library/functions.html#super

    Queston 21: 关于继承object的问题:

    class A: def foo(self): print('called A.foo()') class B(A): pass class C(A): def foo(self): print('called C.foo()') class D(B, C): pass if __name__ == '__main__': d = D() d.foo()

    作者:邹冲 链接:https://www.zhihu.com/question/19754936/answer/202650790 来源:知乎 著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

    Queston 22: 关于参数*args和**kwargs:

    *args是一个tuple,表示任何多个无名参数;kwargs是一个dict,表示关键字参数。同时使用它们两个时,*args参数要在kwargs前

    部分REF: RUNOOB

    转载请注明原文地址: https://ju.6miu.com/read-6202.html

    最新回复(0)