• python coroutine的运行过程

    说明 1、先调用函数获取生成器对象,再调用next方法或send(None)方法打开coroutine。 2、打开后,函数执行到yield位置,返回yield后挂起,把控制流交回主线程。再调用send法时,可以传输数据并激活协程,继续执行到最后或下一个yield语句。 实例 “”” # BEGIN CORO_AVERAGER_TEST     >>> coro_avg = averager()  # <1>     >>> next(coro_av…

    影音 2021年6月24日
  • python Future的两种使用

    1、通过submit提交任务创建获得任务的future对象,通过as_completed等待future对象结束,获得结果。as_completed接收future对象的迭代器。 with concurrent.futures.ThreadPoolExecutor(max_workers=5) as executor:     # Start the load operations and mark each future with its URL     future_to_url = {ex…

    影音 2021年6月24日
  • python else在循环语句执行的情况

    1、当循环体没有执行break的时候,即循环体正常结束。 print(“两次输入机会”) for i in range(2):     num = int(input(“请输入一个数字:”))     if 10 == num:         print(“10 == num,触发break,不会执行else子句”)         break else:     print(“循环体没有执行break语句,执行else子句”) print(“程序结束”) 当没有触发break时,执行else…

    影音 2021年6月24日
  • python爬虫采集遇到的问题及解决

     1、编码问题。 网站目前最多的两种编码:utf-8,或者gbk,当我们采集回来源网站编码和我们数据库存储的编码不一致时,比如http://163.com的编码使用的是gbk,而我们需要存储的是utf-8编码的数据,那么我们可以使用Python中提供的encode()和decode()方法进行转换,比如:content = content.decode(‘gbk’, ‘ignore’)   #将gbk编码转为unicode编码。 content = content.encode(‘utf-8’,…

    影音 2021年6月24日
  • python pprint.pformat()函数的使用

    1、pprint.pformat()函数返回要打印的内容的文本字符串,这个字符串既易于阅读,也是语法上正确的Python代码。 import  pprint cats = [{‘name’:’Zophie’,’desc’:’chubby’},{‘name’:’Pooka’,’desc’:’fluffy’}] pprint.pformat(cats)   fileObj = open(‘myCats.py’,’w’) fileObj.write(‘cats = ‘+pprint.pformat(c…

    影音 2021年6月24日
  • python使用shelve保存变量

    1、用shelve模块,可以将Python中的变量保存到二进制的shelf文件中。这样,程序就可以从硬盘中恢复变量的数据。 import shelve shelfFile = shelve.open(‘mydata’) cats = [‘Zonphie’,’Pooka’,’Simon’] shelfFile[‘cats’] = cats shelfFile.close() 2、shelf值不必用读模式或写模式打开,因为打开后,既能读又能写。 shelfFile = shelve.open(‘my…

    影音 2021年6月24日
  • python路径的有效性检查

    说明 1、os.path.exists(path):如果path参数所指的文件或文件夹存在,则返回True,否则返回False。 2、os.path.isfile(path):如果path参数存在,并且是一个文件,则返回True,否则返回False。 3、os.path.isdir(path):如果path参数存在,并且是一个文件夹,则返回True,否则返回False。 实例 ##路径有效性检查 print(os.path.exists(‘C:\\Windows’)) print(os.path…

    影音 2021年6月24日
  • python format()的下标匹配

    说明 1、当format()中的参数为元组、列表或字典时,在字符串模板中使用下标0[0]或key 0[key]来指定引用关系。 2、元组、列表或字典仍使用位置编号。 实例 >>> para=(“Tome”,”cat”) >>> “Hello {0[0]}’s {0[1]}”.format(para) “Hello Tome’s cat” >>> “Hello {0[0]}’s {0[1]}”.format(para) “Hello Tome’…

    影音 2021年6月24日
  • python有哪些匹配替换

    1、位置匹配 字符串模板中,直接使用{}一对大括号,与format()中的参数,按照大括号位置匹配。 >>> “{}”.format(1) ‘1’ >>> “Hello {}’s {}”.format(“Tom”,”cat”) “Hello Tom’s cat” >>> “{{Hello}} {}’s {}”.format(“Tom”,”cat”) “{Hello} Tom’s cat” 2、编号匹配 {0},{1}…大括号中,可以加入f…

    影音 2021年6月24日
  • python中%格式表达式如何使用

    1、通过%格式表达式可以构建对象的格式化字符串输出。%表达式,由%分隔,左侧为格式字符串,由固定字符串和%开头的格式化样式组成,右侧为实际的对象,或对象元组。 >>> ‘%o’ % 10 ’12’ >>> ‘%.3f’ % 0.1234 ‘0.123’ >>> ‘%-10s’ % ‘abcdefg’+’___’ ‘abcdefg   ___’ >>> ‘Sum = %d’ % 5050 ‘Sum = 5050’ >&g…

    影音 2021年6月24日