python调用摄像头

打开摄像头

import cv2
import numpy as np

def video_demo():
    capture = cv2.VideoCapture(0)#0为电脑内置摄像头
    while(True):
        ret, frame = capture.read()#摄像头读取,ret为是否成功打开摄像头,true,false。 frame为视频的每一帧图像
        frame = cv2.flip(frame, 1)#摄像头是和人对立的,将图像左右调换回来正常显示。
        cv2.imshow("video", frame)
        c = cv2.waitKey(50)
        if c == 27:
            break
video_demo()
cv2.destroyAllWindows()

pyechart实现可移动图表

from pyecharts import options as opts
from pyecharts.charts import Bar, Grid, Line, Liquid, Page, Pie
from pyecharts.faker import Faker
from pyecharts.globals import SymbolType

#饼状图
def pie():
    c = (
        Pie()
        .add("", [['跳水', 12], ['射击', 11], ['举重', 8], ['竞技体操', 8], ['乒乓球', 7], ['游泳', 6], ['羽毛球', 6], ['田径', 5], ['静水皮划艇', 3], ['蹦床体操', 3], ['自由式摔跤', 3], ['赛艇', 3], ['空手道', 2], ['拳击', 2], ['帆船', 2], ['花样游泳', 2], ['跆拳道', 1], ['场地自行车赛', 1], ['古典式摔跤', 1], ['击剑', 1], ['三人篮球', 1]],center=["50%", "60%"],)
        .set_series_opts(label_opts=opts.LabelOpts(formatter="{b}: {c}"))
#         .render("饼图.html")
        )
    return c
#     return c.render_notebook()

#水滴图
def wb():
    c = (
        Liquid()
        .add("", [0.3, 0.7], is_outline_show=False, shape=SymbolType.DIAMOND)
        .set_global_opts(title_opts=opts.TitleOpts(title="Liquid-Shape-Diamond"))
#         .render("liquid_shape_diamond.html")
        )
    return c
#     return c.render_notebook()

#柱状图
def bar():
    c = (
        Bar()
        .add_xaxis(Faker.choose())
        .add_yaxis("商家A", Faker.values(), stack="stack1")
        .add_yaxis("商家B", Faker.values(), stack="stack1")
        .set_series_opts(label_opts=opts.LabelOpts(is_show=False))
        .set_global_opts(title_opts=opts.TitleOpts(title="Bar-堆叠数据(全部)"))
#         .render("bar_stack0.html")
        )
    return c
#     return c.render_notebook()
page = Page(layout=Page.DraggablePageLayout, page_title="2020东京奥运会奖牌榜")

# 在页面中添加图表
page.add(
    pie(),
    wb(),
    bar())
page.render('test.html')

python获取底层硬件信息

CPU 架构

import platform
print("操作系统名称及版本号:",platform.platform())    #获取操作系统名称及版本号
print("操作系统版本号:",platform.version())           #获取操作系统版本号
print("操作系统的位数:",platform.architecture())      #获取操作系统的位数
print("计算机类型:",platform.machine())               # 计算机类型
print("计算机网络名称:",platform.node())             #计算机网络名称
print("计算机处理器信息:",platform.processor())       #计算机处理器信息
print("上面所有的信息汇总:",platform.uname())         #上面所有的信息汇总

CPU 核数

# 方法一:
# 如果当前Python版本大于2.6,可以简单的通过下面模块来获取当前cpu数量,
import multiprocessing
print("CPU 核数:",multiprocessing.cpu_count())
# 如果是比较老的Python版本,可以用下面的模块来获取当前cpu数量:
import psutil
print("CPU 核数:",psutil.cpu_count())

# 方法二:
# Python可以读系统文件/proc/cpuinfo,过滤“processor”字段统计核心数。
def get_cpu_info():
    processor_cnt = 0
    cpu_model = ""
    f_cpu_info = open("/proc/cpuinfo")
    try:
        for line in f_cpu_info:
#             print(line)
            if (line.find("processor") == 0):
                processor_cnt += 1
        print("cpu counts:{}" .format(processor_cnt))
    finally:
        f_cpu_info.close()
get_cpu_info()

内存信息

# 读取内存信息可以直接读系统文件/proc/meminfo。
def get_mem_info():
    mem_info = ""
    f_mem_info = open("/proc/meminfo")
    try:
        for line in f_mem_info:
#             print(line.strip())
            if (line.find("MemTotal") == 0):
                mem_info += line.strip()+ ", "
            elif (line.find("SwapTotal") == 0):
                mem_info += line.strip()
                break;
        print("mem_info---- {:s}".format(mem_info))
    finally:
        f_mem_info.close()
get_mem_info()

磁盘信息

import os
import subprocess
def get_disc_info():
#     方法一:
    disc_info=os.popen("df -h").read()
    disc_info=subprocess.Popen("df -h",shell=True).communicate()[0]
    print(disc_info)

# 方法二:
#     pipe=subprocess.Popen("df -h",stdout=subprocess.PIPE,shell=True)
#     disc_info=pipe.stdout.read()
#     print(disc_info)
get_disc_info()

网络信息

import netifaces
routingGateway = netifaces.gateways()['default'][netifaces.AF_INET][0] #网关
routingNicName = netifaces.gateways()['default'][netifaces.AF_INET][1] #网络适配器信息
for interface in netifaces.interfaces():
    if interface == routingNicName:
        #print (netifaces.ifaddresses(interface))
        try:
            routingIPAddr = netifaces.ifaddresses(interface)[netifaces.AF_INET][0]['addr'] #获取IP
        except KeyError:
            pass
    #print ("Routing IP Address:%s"% routingIPAddr)
    return routingIPAddr
if __name__ == "__main__":
    try:
        print ("Routing IP Address:",GetNetworkIP())
    except:
        print ("Unable to get the address, there may not be installed netifaces module! command:pip install netifaces")

爬取QQ音乐流行指数榜

import requests
import re
def Get_HTML(url):
    headers={'User-Agent':'Mozilla/5.0'}
    try:
        r=requests.get(url,headers=headers)
        r.raise_for_status()
        r.encoding=r.apparent_encoding
        return r.text
    except:
        print("error!")
def ParsePage(html):
    pattern=re.compile('<div class="songlist__songname">.?<a title="(.?)" href.?>.?</a>.?<div class="songlist__artist">.?<a class.?>(.?)</a>',re.S)
    items=re.findall(pattern,html)
    return items
def Print(items):
    name=[]
    tplt="{0:^10}{1:^25}{2:^25}"
    print("{0:^10}{1:^25}{2:^18}".format("排名","歌名","歌手",chr(12288)))
    for i in range(20):
        print(tplt.format(i+1,itemsi,itemsi),chr(12288))
def main():
    url='https://y.qq.com/n/ryqq/toplist/4';
    html=Get_HTML(url)
    items=ParsePage(html)
    Print(items)
main()

re和pyquery练习(爬取1905电影网)

正则表达式
import requests
import re
import json
from lxml import etree
from bs4 import BeautifulSoup
from pyquery import PyQuery as pq
"获取html文档"
def Get_HTML(url):
headers={'User-Agent':'Mozilla/5.0'}
try:
    r=requests.get(url,headers=headers)
    r.raise_for_status()
    r.encoding=r.apparent_encoding
    return r.text
except:
    print("Error!")
"设置正则表达式规则,获取信息"
def parse_pages(html):
pattern=re.compile('<dl.?cl">.?nob.?>(.?)</b>.?class="li03 oh".?href="(.?)".?class=" pl28">(.?)</a>.?<span>.?title=.?>(.?)</a>.?title=.?>(.?)</a>.?title=.?>(.?)</a>.?class="li05 ta_c".?<span>(.?)</span>.*?</dl>',re.S)
items=re.findall(pattern,html)
for item in items:
    yield{
        'index':item[0],
        'image':item[1],
        'title':item[2],
        'actor':item[3:6],
        'score':item[6]
        } 
def main():
url='https://www.1905.com/vod/top/lst/';
html=Get_HTML(url)
for item in parse_pages(html):
    print(item)
    #Write_to_file(item) 
main()

pyquery
from pyquery import PyQuery as pq
import requests
import re
import json

def Get_HTML(url):
    headers = {'User-Agent': 'Mozilla/5.0'}
    try:
        r = requests.get(url, headers=headers)
        r.raise_for_status()
        r.encoding = r.apparent_encoding
        return r.text
    except:
        print("Error!")

def parse_page(html):
    doc=pq(html)
    title=doc('.li03 a').text().split(' ')  #名称
    actor=doc('.li04 span').text().split(' ')  #演员表
    index=doc('.li01 b').text().split(' ')     #序号
    href=[]  #链接
    for i in doc('.li03 a').items():  #遍历
        href.append(i.attr('href'))
    score=doc('.li05 span').text().split(' ')  #评分
    Result={}
    for i in range(100):
        result={
            '序号':index[i],
            '名称':title[i],
            '链接':href[i],
            '演员':actor[i],
            '评分':score[i]
        }
        Result[index[i]]=result
    return Result
def write_to_file(item):
    with open('1905电影排行榜.txt', 'a+', encoding='UTF-8') as f:
        f.write(json.dumps(item, ensure_ascii=False) + '\n')
def main():
    url = 'https://www.1905.com/vod/top/lst/'
    html = Get_HTML(url)
    item=parse_page(html)
    for i in range(1,len(item)+1):
        write_to_file(item[str(i)])

main()