from tkinter import *
def f():
w = int(e1.get()) + int(e2.get()) - int(e3.get())
wage.insert(0,w)
root = Tk()
root.title("工资计算器")
Label(root, text="每月基本工资:").pack()
e1 = Entry(root)
e1.pack()
Label(root, text="补助工资:").pack()
e2 = Entry(root)
e2.pack()
Label(root, text="考勤扣款:").pack()
e3 = Entry(root)
e3.pack()
Button(root, text="计算", command=f).pack()
Label(root, text="实发工资:").pack()
wage=Entry(root)
wage.pack()
root.mainloop()
from PIL import Image
from wordcloud import WordCloud
import jieba
import numpy as np
#2、读取文本并分词
text = open("2023政府工作报告.txt","rb").read()
ss=" ".join(jieba.lcut(text))
mask=np.array(Image.open("ChinaMap.png"))
#3、配置词云参数,生成词云
wc = WordCloud(
font_path="fonts/msyh.ttc",
background_color = "white",
max_words=300,
mask =mask,
max_font_size = 200,height=400,width=854,
stopwords={"的", "了", "是", "在", "和", "有", "一个", "与", "我", "我们", "你", "他", "她", "它", "这个", "那个", "对于",
"因为", "所以", "如果", "如何", "这样", "但", "只有", "而", "也", "更加", "去", "将", "可以", "大", "小", "非常",
"不仅", "更", "是的", "以及", "而且", "关于", "当", "能", "这些", "这些", "自己", "需要", "当时", "某些", "任何",
"本", "此", "更", "过", "一些", "同样", "两", "三", "四", "五", "十", "不", "多", "少", "起来", "之前", "之后"},
colormap="Reds",contour_width=8,contour_color="red")
wc.generate(ss)
#4、生成图片并显示
wc.to_image( )
wc.to_file("C:/Users/Administrator/Desktop/new.png")
font,background_color,max_words,mask,stopwords
wc.generate(ss)
生成词云#日期、天气如何、温度、风向、风速
import requests
from bs4 import BeautifulSoup
import time
import xlsxwriter
# 请求网页
def page_request(url, ua):
response = requests.get(url=url, headers=ua)
html = response.content.decode('utf-8')
return html
# 解析网页
def page_parse(html):
soup = BeautifulSoup(html, 'lxml')
date = soup.select('#\\37 d > ul > li> h1')
wendu_high = soup.select('#\\37 d > ul > li > p.tem > span')
wendu_low = soup.select('#\\37 d > ul > li > p.tem > i')
tianqi = soup.select('#\\37 d > ul > li > p.wea')
fenxiang = soup.select('#\\37 d > ul > li > p.win > em > span')
fengsu = soup.select('#\\37 d > ul > li > p.win > i')
workbook= xlsxwriter.Workbook('tianqi.xlsx')
#添加工作表
worksheet=workbook.add_worksheet('data')
headers=['日期','温度','天气','风向','风速']
for col_num,headers in enumerate(headers):
worksheet.write(0,col_num,headers)
for i in range(6):
print(date[i].get_text()+'\t'+wendu_low[i].get_text()+'\t'+wendu_high[i].get_text()+'\t'+tianqi[i].get_text()+'\t'+fenxiang[i].get_text()+'\t'+fengsu[i].get_text())
data=[date[i].get_text(),wendu_low[i].get_text()+'-'+wendu_high[i].get_text(),tianqi[i].get_text(),fenxiang[i].get_text(),fengsu[i].get_text()]
for col_num,value in enumerate(data):
worksheet.write(i+1,col_num,value)
workbook.close()
if __name__ == "__main__":
print('**************开始爬取七日天气**************')
ua = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/90.0.4421.5 Safari/537.36'}
# 豆瓣电影Top250每页有25部电影,start就是每页电影的开头
url = "https://www.weather.com.cn/weather/101180101.shtml"
html = page_request(url=url, ua=ua)
page_parse(html=html)
#print('**************爬取完成**************')
分成三个部分
- 对网页的请求
- 解析网页,返回html
- 对html进行处理
详细叙述第三部分
page_prase方法
,首先soup = BeautifulSoup(html, 'lxml')
将处理后的html保存在soup里边
然后使用soup.select
方法将天气,最高最低温度,风速,风向,日期都创建变量进行保存
这一部分添加工作表并进行保存
workbook= xlsxwriter.Workbook('tianqi.xlsx')
#添加工作表
worksheet=workbook.add_worksheet('data')
headers=['日期','温度','天气','风向','风速']
for col_num,headers in enumerate(headers):
worksheet.write(0,col_num,headers)
for i in range(6):
print(date[i].get_text()+'\t'+wendu_low[i].get_text()+'\t'+wendu_high[i].get_text()+'\t'+tianqi[i].get_text()+'\t'+fenxiang[i].get_text()+'\t'+fengsu[i].get_text())
data=[date[i].get_text(),wendu_low[i].get_text()+'-'+wendu_high[i].get_text(),tianqi[i].get_text(),fenxiang[i].get_text(),fengsu[i].get_text()]
for col_num,value in enumerate(data):
worksheet.write(i+1,col_num,value)
最后workbook.close()将该工作表进行保存
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def say_hello(self):
print(f"Hello, my name is {self.name} and I am {self.age} years old.")
if __name__=="__main__":
person1 = Person("Alice", 25)
person1.say_hello()
def key(list1,list2):
list3=[]
list4=[]
for i in list1:
if i%2==0:
list3.append(i)
for i in list2:
if i%2==0:
list3.append(i)
for i in list1:
if i%2!=0:
list4.append(i)
for i in list2:
if i%2!=0:
list4.append(i)
list3=sorted(list3)
list4=sorted(list4)
print(list4+list3)
if __name__ == '__main__':
list1=[1,5,8,2,22,9,7,20,25,24,99]
list2=[111,112,113,114,115,116,117]
key(list1,list2)
列表(list
)和元组(tuple
)是 Python 中两种常用的数据结构,它们之间有以下几个主要区别:
列表(List)
列表是可变的,可以修改元素的值、添加元素或删除元素。
python复制代码lst = [1, 2, 3]
lst[0] = 10 # 修改元素
lst.append(4) # 添加元素
lst.remove(2) # 删除元素
print(lst) # [10, 3, 4]
元组(Tuple)
元组是不可变的,一旦创建,不能修改其元素或结构。
python复制代码tpl = (1, 2, 3)
# tpl[0] = 10 # 会报错:TypeError: 'tuple' object does not support item assignment
print(tpl) # (1, 2, 3)
列表使用方括号
[]
表示。
python
复制代码
lst = [1, 2, 3]
元组使用圆括号
()
表示。如果元组只有一个元素,需加逗号。
python复制代码tpl = (1, 2, 3)
single_tpl = (1,) # 单元素元组
#解释python中的异常处理机制
# 1. 异常处理机制
# 在程序运行的过程中,可能会出现各种各样的异常,比如输入错误、文件操作失败等等。如果不对这些异常进行处理,程序将会终止运行,并给出错误提示。
# 为了避免程序终止运行,我们需要对可能出现的异常进行处理,并给出合适的提示信息。
# Python中提供了try...except...finally语句来处理异常。
# try语句用来包含可能出现异常的语句,except语句用来处理异常,finally语句用来执行一些清理工作,无论是否出现异常都会执行。
#演示代码如何捕获并处理ZeroDivisionError异常:
try:
a = 1 / 0
except ZeroDivisionError:
print("division by zero!")
# 运行上述代码,将会输出"division by zero!",说明程序正常运行,并捕获到了ZeroDivisionError异常。
import numpy as np
import matplotlib.pyplot as plt
from matplotlib import gridspec
# 定义函数 y = e^(2x) * cos(3πx + π/3)
def f(x):
return np.exp(2 * x) * np.cos(3 * np.pi * x + np.pi / 3)
# 设置 x 的范围
x_range = np.linspace(0, 10)
# 创建图形,设置自定义布局
fig = plt.figure(figsize=(8, 12))
# 使用 gridspec 设置布局
gs = gridspec.GridSpec(2, 1, height_ratios=[2, 1]) # 上方大图占2/3, 下方小图占1/3
# 创建子图1:步长 0.2
ax1 = plt.subplot(gs[0]) # 上面的大图
x1 = np.arange(0, 10, 0.2)
y1 = f(x1)
ax1.plot(x1, y1, label='Step = 0.2', color='b', linestyle='-', marker='o')
ax1.set_title('Step Size = 0.2')
ax1.set_xlabel('x')
ax1.set_ylabel('y')
ax1.grid(True)
ax1.legend()
# 创建子图2和子图3:分别为步长 0.5 和 0.7,放在底部
gs2 = gridspec.GridSpecFromSubplotSpec(1, 2, subplot_spec=gs[1]) # 在底部创建两个子图
# 子图2:步长 0.5
ax2 = plt.subplot(gs2[0])
x2 = np.arange(0, 10, 0.5)
y2 = f(x2)
ax2.plot(x2, y2, label='Step = 0.5', color='g', linestyle='--', marker='x')
ax2.set_title('Step Size = 0.5')
ax2.set_xlabel('x')
ax2.set_ylabel('y')
ax2.grid(True)
ax2.legend()
# 步长 0.7
ax3 = plt.subplot(gs2[1])
x3 = np.arange(0, 10, 0.7)
y3 = f(x3)
ax3.plot(x3, y3, label='Step = 0.7', color='r', linestyle='-.', marker='s')
ax3.set_title('Step Size = 0.7')
ax3.set_xlabel('x')
ax3.set_ylabel('y')
ax3.grid(True)
ax3.legend()
# 调整布局
plt.tight_layout()
# 显示图形
plt.show()
import pandas as pd
import matplotlib.pyplot as plt
# 读取数据
df=pd.read_excel('sales.xlsx',parse_dates=['date'])
print(df.head())
# 按店铺分组并计算销售和利润的总和
store_sales=df.groupby("store")[["sales","profit"]].sum()
print(store_sales)
# 绘制柱状图
# 筛选出销售额大于200的记录
high_sales=df[df["sales"]>200]
print(high_sales)
# 按类别分组并计算利润的平均值
category_profit=df.groupby("category")["profit"].mean()
print(category_profit)
# 绘制各店铺总销售额的柱状图
store_sales["sales"].plot(kind="bar",figsize=(10,6),color="skyblue")
plt.title("Total Sales by Store")
plt.xlabel("Store")
plt.ylabel("Total Sales")
plt.show()