写一百题程序学Python 【 31-35】

31. Python多线程的使用

流程:定义程序,建立新线程,主线程进入死循环(不然程序就结束了),子线程循环执行

import _thread
import time

def print_time(threadName,delay):
    count = 0
    while count < 5:
        time.sleep(delay)
        count += 1
        print("%s:%s" % (threadName,time.ctime(time.time())))
        
#建立两个新的线程
try:

    _thread.start_new_thread(print_time,("thread-1",2)) #传入函数名称,传入函数参数
    _thread.start_new_thread(print_time, ("thread-2",3))
except:
    print("Can't create thread")

while 1:
        pass


32.Python错误处理,构建一个不存在的prints函数,因为是脚本语言因此前期不会检查到错误,只有解释时候才会检测到错误并且返回错误值

import _thread
import time

def prints(str):
    print(str+"s")

try:
    print("hello")
    prints("mod")
except Exception as er:
    print(er)


33. Python读取文件,流程是使用open函数打开txt文本文件,写入文件然后关闭文件,再以读取方式打开文件

import _thread
import time

def prints(str):
    print(str+"s")

try:
 fh1 = open("e:/c6.txt","w")
 fh1.writelines("line1")
 fh1.close()
 fh2 = open("e:/c6.txt","r")

 print(fh2.readline())
except Exception as er:
    print("Open file failure")
    print(er)


34.Python使用正则表达式检索字符串

简单的搜索baidu在网址字符串中的位置

import re
pat="baidu"  
string = "http://www.baidu.com"
rst1 = re.search(pat,string)
print(rst1)

执行结果:<_sre.SRE_Match object; span=(11, 16), match='baidu'>


35.Python使用正则表达式提取网页

加载一个课程预定的页面,利用正则表达式提取出网页指定标签(strong标签内)的内容

 
import re
import urllib.request

pat="<strong>[\\x0a-\\xf0](.*?)</strong>"
data =urllib.request.urlopen( "https://edu.csdn.net/huiyiCourse/detail/819").read()
rst1 = re.compile(pat).findall(str(data))
print(rst1)






  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值