• python异常的捕捉和补救

    1、捕捉特定异常 第一个符合条件的except语句会被执行,用于报告错误。如果仅仅是报告错误,程序依然会停止。 a = 0 try:     b = 5/a except ZeroDivisionError:     print(‘Error: a不能为0’) except ValueError:     print(‘Error: 传入参数无效’) 2、捕捉所有异常 except语句后面Exception表示捕获任何异常类型。 a = 0 try:     b = 5/a except Exc…

    影音 2021年6月24日
  • python如何输入数据类型检查

    说明 1、数据类型检测可以使用内置函数isinstance()来实现。 2、内置函数isinstance有两个参数,第一个参数是需要检测的对象,第二个参数是对象类型,可以是单一类型,也可以是元组,返回bool类型。 实例 def my_abs(x):      if not isinstance(x, (int, float)):         raise  TypeError(‘bad operand type’)      if x>=0:         return x     …

    影音 2021年6月24日
  • 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日