1.数据库模糊查询
import sqlite3
import random
con = sqlite3.connect('nameDB')
cursor = con.cursor()
cursor.execute('create table if not exists nameTable (name text)')
con.commit()
str = """
赵钱孙李,周吴郑王。
冯陈褚卫,蒋沈韩杨。
朱秦尤许,何吕施张。
孔曹严华,金魏陶姜。
戚谢邹喻,柏水窦章。
云苏潘葛,奚范彭郎。
鲁韦昌马,苗凤花方。
俞任袁柳,酆鲍史唐。
费廉岑薛,雷贺倪汤。
一二三四,东西南北。
"""
str = str.replace(',','').replace('。','').replace('\n','')
print(str)
# for x in range(1000):
# name = ''
# for y in range(random.randint(2,4)):
# char = random.choice(str)
# name+=char
# print(name)
# cursor.execute('INSERT INTO nameTable (name) VALUES ("{}")'.format(name))
# con.commit()
def get_all_match_info():
# 张_ :表示找到以张开头的后面只有一位数据
# __多少位 就代表找到后面几位的数据
# LIKE :是数据库进行匹配的关键字 后面是匹配的规则
# cursor.execute('SELECT * FROM nameTable WHERE name LIKE "张_"')
# cursor.execute('SELECT * FROM nameTable WHERE name LIKE "_王"')
# %李表示找到以李结束的数据 李%:表示找到以李开头的数据
# cursor.execute('SELECT * FROM nameTable WHERE name LIKE "李%"')
# %陈% : 表示找到所有包含陈的数据
cursor.execute('SELECT * FROM nameTable WHERE name LIKE "陈%"')
print(cursor.fetchall())
get_all_match_info()
2.闭包
def outSide(a,b):
def inSide():
return a+b
return inSide
result=outSide(5,6)
print(result())
# 闭包:外层函数包含内层函数,同时内层函数使用外层函数的参数
# 并且将内层函数返回出去,这种结构称之为闭包
# 1.函数包裹函数
# 2.内层使用外层函数的参数
# 3.内层函数当成返回值
3.属性插槽
name = '小陈'
age = 20
print('{},{}'.format(name,age))
print('{},{}'.format(age,name))
class People(object):
def __init__(self,name='',age=''):
self.name=name
self.age=age
p = People('陈烨',23)
print(p.name)
print(p.age)
# 给对象添加一个属性 无则添加 有责修改
p.fond='学习'
print(p.fond)
class Person(object):
# slots:插槽
# 只支持本类添加[]里面包含的属性
__slots__ = ['name','age']
def __init__(self,name,aeg):
self.name=name
self.age=age
p1=Person('xiao',22)
print(p1.name)
print(p1.age)
# AttributeError: 'Person' object has no attribute 'dog' 因为有插槽所有不能扩展 只能有name和age
# p1.dog ='哮天犬'
# print(p1.dog)
4.数据请求
# url:网址 library 地址库
# request:请求
# parse:解析 quote:引用
from urllib.request import urlopen
from urllib.parse import quote
import string
import json
from prettyprinter import pprint
url = 'https://www.apiopen.top/weatherApi?city=郑州'
# url不能写中文 之所以能看到英文是因为浏览器处于友好的目的
# 为了让用户识别特意显示的但是url执行的时候 中文会转码
# 如果不进行转码 程序会出错
response = urlopen(quote(url,safe = string.printable))
# urlopen 不支持中英混码
responsedate = response.read()
print(responsedate)
# 地址栏不支持使用中文,所以需要进行转码
# 转码的时候 不但会将中文进行转码
# 同时也会将一些特殊符号进行转码 比如:?
# 如果不想让这些特殊符号进行转码
# 就要使用完全转码(只会转码中文)
print('没有使用safe\n{}'.format(quote(url)))
print('使用了safe\n{}'.format(quote(url,safe=string.printable)))
responseJson = json.loads(responsedate)
pprint(responseJson)
习题:
import sqlite3
from urllib.request import urlopen
from urllib.parse import quote
import string
import json
from xpinyin import Pinyin
p = Pinyin()
class weather(object):
def __init__(self,citylist=[]):
self.citylist=citylist
self.connect = None
self.cursor=None
# self.cityname=''
def getallinfo(self):
#打开/创建数据库
self.openDB()
# for city in self.citylist:
# self.cityname=city
# # print(self.cityname)
for city in self.citylist:
cityname=p.get_pinyin(city).replace('-','')
self.cursor.execute('create table if not exists "{}" (day text,high text,low text)'.format(cityname))
self.connect.commit()
url = 'https://www.apiopen.top/weatherApi?city={}'.format(city)
#获取响应对象
response = urlopen(quote(url,safe=string.printable))
responsestr = response.read()
#将文本转化为字典
responseDic = json.loads(responsestr)
self.cursor.execute('insert into "{}" (day,high,low) VALUES ("{}","{}","{}")'.format(cityname,responseDic['data']['yesterday']['date'],
responseDic['data']['yesterday']['high'],
responseDic['data']['yesterday']['low']))
for otherDate in responseDic['data']['forecast']:
self.cursor.execute('insert into "{}" (day,high,low) VALUES ("{}","{}","{}")'.format(cityname,otherDate['date'],
otherDate['high'],
otherDate['low']))
self.connect.commit()
def getinfowith(self,info):
info['city'] = p.get_pinyin(info['city']).replace('-','')
self.openDB()
self.cursor.execute('select * from "{}" WHERE day LIKE "%{}%"'.format(info['city'],info['time']))
self.connect.commit()
result = self.cursor.fetchall()
print(result)
def openDB(self):
self.connect = sqlite3.connect('weatherBIUBIUBIU')
self.cursor = self.connect.cursor()
def closeDB(self):
self.connect.commit()
self.cursor.close()
self.connect.close()
w = weather(['开封','南阳','信阳','驻马店','商丘','周口'])
# w.getallinfo()
dic = {}
dic['city']=input('你像查询哪个城市')
dic['time']=input('你想查询哪一天')
w.getinfowith(dic)
from urllib.request import urlopen
from urllib.parse import quote
import string
import json
import sqlite3
class dianying(object):
def __init__(self,dbname='',tablename=''):
self.dbname=dbname
self.tablename=tablename
self.connect =None
self.cursor = None
def getalldianying(self):
self.connect=sqlite3.connect('{}'.format(self.dbname))
self.cursor = self.connect.cursor()
self.cursor.execute('create table if not exists "{}"(title text,year text,average text,name text)'.format(self.tablename))
self.connect.commit()
url = 'https://api.douban.com/v2/movie/us_box'
response = urlopen(quote(url, safe=string.printable))
responseStr = response.read()
responseDic = json.loads(responseStr)
for dict in responseDic['subjects']:
title=dict['subject']['title']
year=dict['subject']['year']
average=dict['subject']['rating']['average']
name1=[]
for x in dict['subject']['casts']:
name1.append(x['name'])
self.cursor.execute('INSERT INTO "{}" (title,year,average,name) VALUES ("{}","{}","{}","{}")'.format(self.tablename,title, year,average,name1))
self.connect.commit()
def getalldy(self,info):
info.movename=f.movename
self.connect=sqlite3.connect('{}'.format(self.dbname))
self.cursor=self.connect.cursor()
self.cursor.execute('select * from "{}" WHERE title="{}"'.format(self.tablename ,info.movename))
self.connect.commit()
result=self.cursor.fetchall()
print(result)
class fans(object):
def __init__(self,movename=''):
self.movename=movename
dian = dianying('dianyingDB','dianying')
dian.getalldianying()
f = fans()
f.movename=input('请输入你想看的电影名称')
dian.getalldy(f)