Python-爬虫-数据库Mysql、正则表达式简单练习
2019-11-15 本文已影响0人
MonkeyLei
官方教程来
re --- 正则表达式操作 - Python 3.7.5 文档
Python3 MySQL 数据库连接 - PyMySQL 驱动
搞起就是了。。其他的自己想到啥需要练习的多敲敲代码就是了
**1. **本地记得安装个mysql,配置环境变量,并且启动起来,创建好需要的数据库,方可模拟!
2. demo_mysql.py - 注释有说明了一些属性。。正则的话,要想搞复杂的,还是得自己多练习,尝试就好。数据库记得做好异常,回收处理
#!/usr/bin/python3
# -*- coding: UTF-8 -*-
# 文件名:demo_mysql.py
# https://www.runoob.com/python3/python3-mysql.html
import pymysql
# 打开数据库
db = pymysql.connect('localhost', 'root', '123456', 'test')
# 创建一个游标操作对象
cursor = db.cursor()
try:
# 使用 execute() 方法执行 SQL,如果表存在则删除
cursor.execute("DROP TABLE IF EXISTS user")
# 创建一个表
sql_c = """create table user(
name char(20) not null,
age int
)
"""
cursor.execute(sql_c)
# 插入一条数据
sql_i = """insert into user values(
'huanglei', 31
)
"""
cursor.execute(sql_i)
db.commit()
# 查询一下
sql_s = """select * from user
"""
cursor.execute(sql_s)
results = cursor.fetchall()
for row in results:
print(row[0], row[1])
except Exception as err:
print(err)
finally:
# 关闭游标
cursor.close()
# 关闭数据库
db.close()
# https://docs.python.org/zh-cn/3.7/library/re.html - 官方教程
import re
# 顺便过下正则,了解下(java的正则之前专门学习了下,都快忘光了)
a = re.match(r'速度[1-8]', '速度1') # r标识不转义
if a:
print(a.pos) # 0
print(a.string) # 速度1
# \d是数字0-9,\D是表示非数字
b = re.match(r'速度\d', '速度110')
if b:
print(b.string)
# \d+ -> 至少一个数字或者无限个数字 接着就是小写字母,大写字母才行
c = re.match(r'速度\d+[a-z][A-z]', '速度120aF')
if c:
print(c.string)
# 来个简单版的11位手机号匹配,1打头,第二位只能是3,4,5,6,7,联通有新的号段6了..建议如果要去不高,直接3-9算了...
d_c = re.compile(r'1[3,4,5,6,7]\d{9}') # 编译成compile对象,能够减少一些特性,加速匹配
d = d_c.match('13111111112')
if d:
print(d.string)
结果:
D:\PycharmProjects\python_study\venv3.x\Scripts\python.exe D:/MEME/fz/doc/Python/python_study/protest/demo_mysql.py
huanglei 31
0
速度1
速度110
速度120aF
13111111112
Process finished with exit code 0
可能暂时的练习就到这里。。要开始看公司的项目,搞下爬页面去了。。。过程中再深入。。。后面还得抽时间继续Android深入学习,练习.....