pyechaarts输出图片

from pyecharts.charts import Bar
from pyecharts import options as opts
from snapshot_phantomjs import snapshot
# 导入输出图片工具
from pyecharts.render import make_snapshot
# 使用snapshot-selenium 渲染图片
from snapshot_selenium import snapshot

# 创建一个柱状图Bar实例

bar = (
    Bar()
    # 添加X轴数据
    .add_xaxis(["衬衫", "羊毛衫", "雪纺衫", "裤子", "高跟鞋", "袜子"])
    # 添加Y轴数据,系列的名称
    .add_yaxis("商家A", [5, 20, 36, 10, 75, 90])
    .add_yaxis("商家B", [8, 15, 60, 20, 25, 30])
    # 添加标题
    .set_global_opts(title_opts=opts.TitleOpts(title="主标题: 双十一销量", subtitle="副标题:服饰类"))
)

# 输出保存为图片
make_snapshot(snapshot, bar.render("./图片.html"), "./003_Options配置项_自定义样式_保存图片.jpeg")
# make_snapshot(snapshot, bar.render(), "./图片.png")

爬取国内疫情数据并可视化

import requests
import json
from lxml import etree
import pandas as pd
import time
from pyecharts import options as opts
from pyecharts.charts import Bar

def sleeptime(hour, min, sec):   #时间转换
    return hour * 3600 + min * 60 + sec

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():
    C_name,Ljqz,Cured,Died,Xcqz,Xzqz=[],[],[],[],[],[]
    url='https://m.look.360.cn/events/feiyan?sv=&version=&market=&device=2&net=4&stype=&scene=&sub_scene=&refer_scene=&refer_subscene=&f=jsonp&location=true&sort=2&_=1649252949072&callback=jsonp2'
    re=Get_HTML(url)
    re=re[7:-2]
    response=json.loads(re)
    for i in range(34):
        c_name=response['data'][i]['data']['provinceName']  #城市名称
        ljqz=response['data'][i]['diagnosed']               #累计确诊
        cured=response['data'][i]['cured']           #治愈
        died=response['data'][i]['died']             #死亡
        xcqz=response['data'][i]['currentConfirmed']   #现存确诊
        xzqz=response['data'][i]['diffDiagnosed']      #新增确诊
        C_name.append(c_name)
        Ljqz.append(ljqz)
        Cured.append(cured)
        Died.append(died)
        Xcqz.append(xcqz)
        Xzqz.append(xzqz)
#     columns=['新增确诊','现存确诊','累计确诊','治愈人数','死亡人数']
#     index=C_name
    data={
        "地区":C_name,
        "新增确诊":Xzqz,
        "现存确诊":Xcqz,
        "累计确诊":Ljqz,
        "治愈人数":Cured,
        "死亡人数":Died
    }
#     print(data)
    return data
def View():
    data=Parse_page()
    c = (
        Bar()
        .add_xaxis(data['地区'])
        .add_yaxis("新增确诊",data['新增确诊'], stack="stack1")
        .add_yaxis("现存确诊",data['现存确诊'] , stack="stack1")
        .add_yaxis("累计确诊",data['累计确诊'] , stack="stack1")
        .add_yaxis("治愈人数",data['治愈人数'] , stack="stack1")
        .add_yaxis("死亡人数",data['死亡人数'] , stack="stack1")
        .set_global_opts(
            title_opts=opts.TitleOpts(title="国内疫情数据数据(全部)"),
            datazoom_opts=opts.DataZoomOpts(type_="inside"),
            )
        .render("国内疫情数据数据.html")
    )
def main():
    data=Parse_page()
    data=pd.DataFrame(data)
    second = sleeptime(24,0,0)
    while True:
#         print(data)
        data.to_csv('./国内疫情数据.csv')
        View()
        time.sleep(second)
# main()

data=Parse_page()
data=pd.DataFrame(data)
data

爬取百度翻译接口

import requests
def BaiDu_fanyi(url):
    kw = input('请输入待翻译的英文/中文单词:')
    data={'kw':kw}
    headers = {
    'User_Agent':'Mozilla/5.0',
    'content-length': str(len(data)),
    'content-type': 'application/x-www-form-urlencoded; charset=UTF-8',
    'referer': 'https://fanyi.baidu.com/',
    'x-requested-with': 'XMLHttpRequest'
    }
    response=requests.post(url,headers=headers,data=data)
#     print(response.json())
# 请输入待翻译的英文/中文单词:word
# {'errno': 0, 'data': [{'k': 'word', 'v': 'n. 单词; 话语; 诺言; 消息 vt. 措辞,用词; 用言语表达 vi. 讲话'}, 
# {'k': 'Word', 'v': '微软公司生产的文字处理软件。; [人名] 沃德'}, {'k': 'words', 'v': 'n. 字( word的名词复数 );
# (说的)话; 诺言; 口令'}, {'k': 'Words', 'v': '[医]言语'}, {'k': 'WORDS', 'v': 'abbr. Western Operational Research Discussion Soci'}]}
    result=''
    for i in response.json()['data']:
        result+=i['v']+'\n'
    print("{}的翻译结果为:".format(kw))
    print(result)
url='https://fanyi.baidu.com/sug'
BaiDu_fanyi(url)

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")