分类 默认分类 下的文章 - 叁零零肆零肆
首页
关于
留言板
友链
搜 索
1
Series和DataFrame
20 阅读
2
在 Ubuntu Server 上安装 JupyterHub,随时随地在网页上写代码
17 阅读
3
字符串
15 阅读
4
Ubuntu 20.04.4 LTS V20220808 安装官方tailscale
14 阅读
5
安装Webmin管理面板
9 阅读
默认分类
登录
/
注册
搜 索
标签搜索
python
Linux
ubuntu
docker
命令
NAS
教程
froxlor
Navidrome
个人音乐
服务器
盒子
字符串
队列
栈
树
二叉树
数组
链表
v2ray
Mo
累计撰写
32
篇文章
累计收到
2
条评论
首页
栏目
默认分类
页面
关于
留言板
友链
用户登录
登录
注册
找到
32
篇与
默认分类
相关的结果
2024-10-15
Python爬取网易云音乐歌单v1.1
运行条件需要安装requests、bs4模块安装方法:cmd进入控制台pip install requestspip install bs4cookie与user-agent获取:登录后进入https://music.163.com/ 根据不同浏览器查看如何查看网站 Cookie在 Google Chrome 中查看 Cookie打开 Chrome 浏览器。访问你想查看 Cookie 的网站。右键点击页面,选择 “检查”(或使用快捷键 Ctrl + Shift + I)。在打开的开发者工具中,选择 “应用程序”(Application)选项卡。在左侧菜单中,找到 “存储”(Storage)部分。点击 “Cookies”,然后选择你当前网站的域名。你将看到网站的所有 Cookie 列表,包括名称、值、域、路径、过期时间等信息。在 Mozilla Firefox 中查看 Cookie打开 Firefox 浏览器。访问你想查看 Cookie 的网站。右键点击页面,选择 “检查元素”(Inspect Element)或使用快捷键 Ctrl + Shift + I。在打开的开发者工具中,选择 “存储”(Storage)选项卡。在左侧菜单中,找到 “Cookies” 部分。点击 “Cookies”,然后选择你当前网站的域名。你将看到网站的所有 Cookie 列表,包括名称、值、域、路径、过期时间等信息。在 Microsoft Edge 中查看 Cookie打开 Edge 浏览器。访问你想查看 Cookie 的网站。右键点击页面,选择 “检查”(Inspect)或使用快捷键 Ctrl + Shift + I。在打开的开发者工具中,选择 “应用程序”(Application)选项卡。在左侧菜单中,找到 “存储”(Storage)部分。点击 “Cookies”,然后选择你当前网站的域名。你将看到网站的所有 Cookie 列表,包括名称、值、域、路径、过期时间等信息。在 Safari 中查看 Cookie打开 Safari 浏览器。访问你想查看 Cookie 的网站。在菜单栏中,选择 “开发”(Develop)> “显示 Web 检查器”(Show Web Inspector)或使用快捷键 Command + Option + I。在打开的开发者工具中,选择 “存储”(Storage)选项卡。点击 “Cookies”,然后选择你当前网站的域名。你将看到网站的所有 Cookie 列表,包括名称、值、域、路径、过期时间等信息。备注确保你的浏览器开发者工具是打开的,以便查看 Cookie 信息。不同浏览器的界面可能会有所不同,但大致步骤相似。python代码# -*- coding:utf-8 -*- import requests,os,json from bs4 import BeautifulSoup print( ''' -------------------------------------- 网易云音乐歌单下载 by:叁零零肆零肆 V 1.1 -------------------------------------- ''' ) headers = { 'Connection': 'close', 'Referer': 'https://music.163.com/', 'Host': 'music.163.com', 'cookie':'', #自己获取 "Accept-Encoding": "identity", "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9" "user-agent":''#自己获取 } s = requests.session() # 保持已登录状态 format = '\t<10}\t' # 输出规则 def get_list(url): # 获取歌单列表 try: response = s.get(url, headers=headers).content # 获取网页 soup = BeautifulSoup(response, 'html.parser') # html格式 lis = list(soup.find('ul')) # 寻找ul标签 father_list = [str(soup.find('h2').string)] # 获取歌单名字到表[0] for i in lis: son_list = [] son_list.append(str(len(father_list)) + '.') # 序号 son_list.append(i.a.string) # 歌曲名称 son_list.append(str(i.a.get('href'))[str(i.a.get('href')).find('=') + 1:-1] + str(i.a.get('href'))[-1]) # 歌曲链接 father_list.append(son_list) # 添加到列表 except: print("\n\t歌曲链接输入错误") # 错误情况 exit('ERROR!') print("从''中找到了条歌曲".format(str(soup.find('h2').string), len(father_list) - 1)) return father_list def mkdir(dir):#创建文件夹 dir = dir.translate() # 将 /\:*?"<>| 文件不能命名的符号去除 isExists=os.path.exists(dir)#判断是否创建了文件夹 if not isExists: os.makedirs(dir)#创建文件夹 print("创建文件夹'%s',将图片放入'%s'文件夹内。"%(dir,dir)) else: print("已经有'%s'文件夹,将图片放入'%s'文件夹内。"%(dir,dir)) def download(list):#根据歌曲列表下载歌曲 print('---------------------------------------------------------------------------------------------------') print('序号 歌曲名称 歌曲链接') for i in list: if list.index(i)==0: continue else: i[1] = i[1].translate() # 将 /\:*?"<>| 文件不能命名的符号去除 print(format.format(i[0], i[1], 'http://music.163.com/song/media/outer/url?id=' + i[2] + '.mp3', chr(12288))) # 排版 # song_url = "https://link.hhtjim.com/163/" + i[2] + ".mp3" # 外链地址 temp_url = "https://api.imjad.cn/cloudmusic/?type=song&id=" + i[2] # 外链地址 temp_jsons = requests.get(temp_url).text temp_list=json.loads(temp_jsons).get('data') song_url=temp_list[0]["url"] song = requests.get(song_url).content # 获取歌曲源 with open(list[0] +'/'+ i[1] + '.mp3', 'wb') as f: # 写入文件夹 f.write(song) f.close() print('---------------------------------------------------------------------------------------------------') print('下载结束!') def download_song(id,url):#根据歌曲列表下载歌曲 response = s.get(url, headers=headers).content # 获取网页 soup = BeautifulSoup(response, 'html.parser') # html格式 name = str(soup.find('em').string) # 获取歌曲名 print('---------------------------------------------------------------------------------------------------') name = name.translate() # 将 /\:*?"<>| 文件不能命名的符号去除 print(format.format(1, name, 'http://music.163.com/song/media/outer/url?id=' + id + '.mp3', chr(12288))) # 排版 temp_url = "https://api.imjad.cn/cloudmusic/?type=song&id=" + id # 外链地址 temp_jsons = requests.get(temp_url).text temp_list=json.loads(temp_jsons).get('data') song_url=temp_list[0]["url"] song = requests.get(song_url).content # 获取歌曲源 with open(name + '.mp3', 'wb') as f: # 写入文件夹 f.write(song) f.close() print('---------------------------------------------------------------------------------------------------') print('下载结束!') choose=input("请选择下载模式\n1为根据歌单ID下载列表歌曲\n2为根据歌曲ID下载单首歌曲\n") if(choose=="1"): search=input("请输入歌单ID:") url="https://music.163.com/playlist?id="+search # 歌单地址 music_list=get_list(url) # 获取歌单列表 mkdir(music_list[0]) # 创建文件夹 download(music_list) # 通过歌单列表下载音乐 elif(choose=="2"): search=input("请输入歌曲ID:") url="https://music.163.com/song?id="+search # 歌曲地址 download_song(search,url) else: print("输入错误!")
2024年10月15日
3 阅读
0 评论
0 点赞
2024-10-15
树莓派通过Python控制舵机
说明使用RPi.GPIO库实现代码# -*- coding: UTF-8 -*- import RPi.GPIO as GPIO import time def servo(angle): GPIO.setmode(GPIO.BOARD) pin1=33#斜台 pin2=35#平台 GPIO.setup(pin1,GPIO.OUT,initial=GPIO.LOW) GPIO.setup(pin2,GPIO.OUT,initial=GPIO.LOW) p1=GPIO.PWM(pin1,50)#设置频率为50KHz,20ms左右的时基脉冲(1/0.020s=50HZ) p2=GPIO.PWM(pin2,50) p1.start(0) p2.start(0) try: p1.ChangeDutyCycle(2.5+angle/360*20)#通过用户输入的角度来改变舵机的角度 time.sleep(0.5)#一秒钟完成转动 p2.ChangeDutyCycle(2.5+180/360*20) time.sleep(0.5) p2.ChangeDutyCycle(2.5+0/360*20) time.sleep(0.5) p1.ChangeDutyCycle(2.5+0/360*20)#通过用户输入的角度来改变舵机的角度 p2.ChangeDutyCycle(2.5+0/360*20) time.sleep(0.5)#一秒钟完成转动0 except KeyboardInterrupt: pass p1.stop() p2.stop() GPIO.cleanup()
2024年10月15日
2 阅读
0 评论
0 点赞
2024-10-15
SQL SERVER数据库日志清理
USE [master] GO ALTER DATABASE blog SET RECOVERY SIMPLE WITH NO_WAIT ----blog为需要清除日志的数据库名称 GO ALTER DATABASE blog SET RECOVERY SIMPLE --简单模式 ----blog为需要清除日志的数据库名称 GO USE blog ----blog为需要清除日志的数据库名称 GO DBCC SHRINKFILE (N'blog_Log' , 11, TRUNCATEONLY) ----blog_Log为需要清除日志的数据库名日志名称 GO USE [master] GO ALTER DATABASE blog SET RECOVERY FULL WITH NO_WAIT ----blog为需要清除日志的数据库名称 GO ALTER DATABASE blog SET RECOVERY FULL --还原为完全模式 ----blog为需要清除日志的数据库名称
2024年10月15日
1 阅读
0 评论
0 点赞
2024-10-15
Windows下通过Python获取链接过的WIFI密码
实现原理是自动化"netsh wlan show profiles"的查询过程,后通过正则匹配获取代码实现# subprocess 模块允许我们启动一个新进程,并连接到它们的输入/输出/错误管道,从而获取返回值 import subprocess import re # 用于判断OS的语言 import locale loc_lang = locale.getdefaultlocale() # print(loc_lang[0]) # 代码中用到的正则匹配模式字符串,提取出来以便不同语言系统使用,默认支持中文英文,其他语言需要更改匹配语句 if loc_lang[0] == "zh_CN": re_pattern = ["所有用户配置文件 : (.*)\r", "安全密钥 : 不存在", "关键内容 : (.*)\r"] else: re_pattern = ["All User Profile : (.*)\r", "Security key : Absent", "Key Content : (.*)\r"] # 如果 capture_output 设为 true,stdout 和 stderr 将会被捕获 cmd_output = subprocess.run(["netsh", "wlan", "show", "profiles"], capture_output=True).stdout.decode('gbk') # print(cmd_output) wifi_names = (re.findall(re_pattern[0], cmd_output)) # print(wifi_names) wifi_list = [] if len(wifi_names) != 0: for name in wifi_names: # 每一个wifi的信息存储在一个字典里 wifi_profile = profile_info = subprocess.run(["netsh", "wlan", "show", "profiles", name], capture_output=True).stdout.decode('gbk') # print(profile_info) # 判断wifi密码是否存储在windows计算机里,不存在则忽略 if re.search(re_pattern[1], profile_info): continue else: wifi_profile["ssid"] = name # 密码存在时,加上命令参数“key=clear”显示wifi密码 profile_info_pass = subprocess.run(["netsh", "wlan", "show", "profiles", name, "key=clear"], capture_output=True).stdout.decode('gbk') password = re.search(re_pattern[2], profile_info_pass) # print(password) if not password: wifi_profile["password"] = None else: wifi_profile["password"] = password[1] wifi_list.append(wifi_profile) for i in range(len(wifi_list)): print(wifi_list[i])
2024年10月15日
1 阅读
0 评论
0 点赞
2024-10-12
wsl2子系统的备份和还原
查看当前WSL版本wsl -lPS C:\windows\system32> wsl -l适用于 Linux 的 Windows 子系统分发:Ubuntu-22.04 (默认)wsl --versionPS C:\windows\system32> wsl --versionWSL 版本: 1.2.5.0内核版本: 5.15.90.1WSLg 版本: 1.0.51MSRDC 版本: 1.2.3770Direct3D 版本: 1.608.2-61064218DXCore 版本: 10.0.25131.1002-220531-1700.rs-onecore-base2-hypWindows 版本: 10.0.19045.2965查看运行中的子系统wsl -l --runningPS C:\windows\system32> wsl -l --running没有正在运行的分发。运行子系统wsl --distribution Ubuntu-22.04PS C:\windows\system32> wsl --distribution Ubuntu-22.04Welcome to Ubuntu 22.04.2 LTS (GNU/Linux 5.15.90.1-microsoft-standard-WSL2 x86_64)Documentation: https://help.ubuntu.comManagement: https://landscape.canonical.comSupport: https://ubuntu.com/advantageStrictly confined Kubernetes makes edge and IoT secure. Learn how MicroK8sjust raised the bar for easy, resilient and secure K8s cluster deployment. https://ubuntu.com/engage/secure-kubernetes-at-the-edgeThis message is shown once a day. To disable it please create the/home/yang/.hushlogin file.停止子系统wsl --terminate Ubuntu-22.04 或 wsl --shutdown (停止当前子系统)PS C:\windows\system32> wsl --terminate Ubuntu-22.04操作成功完成。备份子系统(需要先停止才能备份)wsl --export Ubuntu-22.04 D:\temp\Ubuntu-22.04.tarPS C:\windows\system32> wsl --export Ubuntu-22.04 D:\temp\Ubuntu-22.04.tar正在导出,这可能需要几分钟时间。操作成功完成。卸载子系统wsl --unregister Ubuntu-22.04还原子系统wsl --import [Options]wsl --import Ubuntu-22.04 C:\WSL D:\temp\Ubuntu-22.04.tarNote: 当还原后的子系统变为root权限了改为默认用户权限查看当前用户 ls /home/尝试切换至用户权限 su 用户名切换至root权限 sudo su修改默认配置文件备份 cp /etc/wsl.conf /etc/wsl.conf.bk修改 vim /etc/wsl.conf 在最前面增加以下内容[user]default=用户名 重启wsl,在power shell中重启查看当前运行的wslwsl --list --running停止特定的wslwsl -t Ubuntu-22.04启动特定版本wslwsl -d Ubuntu-22.04或者停止当前所有运行wslwsl --shutdowm启动默认wslwslwsl2迁移与恢复此处记录一下wsl2的迁移,以及当在系统C盘重置系统如何恢复旧版wsl2wsl2迁移这个是建立在已经安装wsl2的基础之上1.查看当前wsl下的Linux是否为关闭状态,当state为Stopped才能进行下一步。wsl -l -v若state为Running时,利用下面的命令结束wsl --shutdown2.以.tar的形式导出到其他盘wsl --export Ubuntu-20.04 e:\Ubuntu-20.04.tar【注】此处导出的Ubuntu-20.04.tar文件可以作为备份文件,下次恢复时直接执行第4步的导入系统就行3.注销原有的linux系统 wsl --unregister Ubuntu-20.044.导入系统 wsl --import Ubuntu-20.04 E:\ubuntu2004 E:\Ubuntu-20.04.tar5.修改默认用户(因为不修改用户名,打开wsl ubuntu之后,默认以root身份登录。)ubuntu.exe config --default-user <--用户名-->用户名是原有wsl ubuntu的用户名称。重装系统恢复旧版wsl2此处是针对重置系统盘,同时旧版wsl2已经迁移到其他盘,如何恢复旧版wsl21.先重新安装一个新的wsl2,这个可以参照网上的wsl2安装教程,注意安装的Ubuntu的版本要和旧版的Ubuntu版本(即你想恢复的Ubuntu)一致2.当安装wsl2成功后,此时wsl2默认安装在系统C盘,然后按照上面的wsl2迁移步骤把wsl2迁移到其他盘3.迁移成功后,把新版的ext4.vhdx删除,拷贝成旧版的ext4.vhdx4.启动wsl2,即可恢复旧版wsl2【注】一定要把新版的ext4.vhdx删除,不能用旧版的去替换新版的ext4.vhdx(即如下图操作是不能恢复到旧版),否则替换成功后,当你启动wsl2会发现还是新版的Ubuntu。Docker 是指容器化技术,用于支持创建和使用 Linux® 容器(LXC技术) 。我们在 Window 上安装 Docker Desktop ,需要基于 Linux 环境。在 Windows上,Docker Desktop 为我们提供通过了两个选项:WSL 与 Hyper-V 。一、WSL2 以及 hyper-v区别,二者安装docker desktop1.WSL2和hyper-v区别简单来说:wsl是一个运行在我下面的解释linux命令的程序,可以直接操作win的资源,又集成了如putty类的集合,不过人家是自己做的。WSL 使用 Hyper-V 架构来实现其虚拟化。。WSL 官方文档(Windows Subsystem for Linux,适用于windows的linux子系统)则是Windows 操作系统的一项特性,可让您直接在 Windows 上运行 Linux 文件系统以及 Linux 命令行工具和 GUI 应用程序,以及传统的 Windows 桌面和应用程序。运行WSL的开销比运行一个虚拟机低很多。WSL 2实际上用的是运行在Hyper-v上的linux内核,相较于虚拟机你不需要很多的性能开销。hyper-v是虚拟机程序,可以提供一个完整的计算机环模拟,与host需要通过网络访问 。Hyper-V 微软官方文档 :让你可以在 Windows 上以虚拟机形式运行多个操作系统,提供硬件虚拟化。在大多数情况下:如果你只使用 Docker : WSL如果你需要Linux,其他的虚拟机或想访问Docker的高级选项卡来分配资源: Hyper-V。2.安装Docker Desktop参考:docker win10专业版下 WSL 2 或 hyper-v 安装Docker Desktop二、docker desktop限额配置,资源配置方法使用WSL2和hyper-v安装的docker,配置是有区别的。1.使用WSL2运行docker:这里会是选择状态:它的配置方法如图所示,需要在用户目录(比如:C:\Users\lc)下建立一个新文件,叫做.wslconfig,修改文件内容为:[wsl2]processors=4memory=8GBswap=8GBlocalhostForwarding=truememory: 表示最大使用 2GB 内存swap: 表示不设置 swaplocalhostForwarding: 默认值为 true。如果 WSL 2 VM 中绑定到通配符或 localhost 的端口应该可以通过 localhost:port 从主机连接。processors: 使用的核心数量,默认和你的 Windows 系统使用的核心数一样重启wsl2:wsl --shutdown2.使用hyper-v运行docker:首先不勾选Use the WSL 2 based engine,然后进入Resources Advanced:修改即可!
2024年10月12日
3 阅读
0 评论
0 点赞
2024-04-26
机顶盒ubuntu更改swap到外置硬盘
1、依次执行以下命令,创建一个空文件,锁定文件的大小。sudo mkdir -v /var/cache/swap cd /var/cache/swap sudo dd if=/dev/zero of=swapfile bs=1K count=4M说明:文件的具体大小建议设定为内存的两倍。此处的1K×4M=4GiB。2、执行以下命令,将新建的文件转换为swap文件。sudo mkswap swapfile3、执行以下命令,给文件授权。sudo chmod 600 swapfile4、执行以下命令,启用swap分区。sudo swapon swapfile5、执行以下命令,进行验证。swapon -s top -bn1 | grep -i swap系统显示类似如下。KiB Swap: 4194300 total, 4194300 free6、执行以下命令,将该分区设置成开机自启。echo "/var/cache/swap/swapfile none swap sw 0 0" | sudo tee -a /etc/fstab7、执行以下命令,测试开机是否加载swap分区。sudo swapoff swapfile sudo swapon -va8、自动挂载swap交换,确保在系统启动后执行。vi /etc/init.d/system-init.sh # 增加如下代码: /bin/sleep 60 # 延迟60秒以确保系统完全启动 /sbin/swapon -va & # 自动加载/etc/fstab文件中设置的swap分区9、如果您需要修改swap使用率,编辑/etc/sysctl.conf文件,修改vm.swappiness值。vm.swappiness=[$NUM]说明:[$NUM]值为swap使用率,取值为0~100。swappiness等于0的时候表示最大限度使用物理内存,然后才使用swap分区;swappiness等于100的时候表示积极的使用swap分区,并且把内存上的数据及时的搬运到swap分区中。
2024年04月26日
4 阅读
0 评论
0 点赞
2024-04-11
高中信息技术(Python) 选择性必修1 数据与数据结构 源代码
第一章 数据与数据的组织1.1 数据1.2数据的组织第二章 数组与链表2.1数组P35 统计分数创建原始分的一维数组s=[0]*9 print(s)创建棋盘二维数组的方式1 直接定义qp=[0,0,0,0],[0,0,0,0],[0,0,0,0],[0,0,0,0] for i in range(4): print(qp[i])创建棋盘二维数组的方式2 间接定义qp=[[0 for i in range(4)]for j in range(4)] for i in range(4): print(qp[i])P37 例2 基于数组实现数据合并的功能from random import randint a=[0]*20 b=[0]*15 c=[0]*35 a[0]=randint(95, 100) for i in range(1,20): a[i]=a[i-1]-randint(1, 5) b[0]=randint(95, 100) for i in range(1,15): b[i]=b[i-1]-randint(1, 5) print("原始数据序列一为:") print(a) print("原始数据序列二为:") print(b) i=0 j=0 k=0 while(i<20 and j<15): if a[i]>=b[j]: c[k]=a[i] i=i+1 k=k+1 else: c[k]=b[j] j=j+1 k=k+1 while i<20: c[k]=a[i] i=i+1 k=k+1 while j<15: c[k]=b[j] j=j+1 k=k+1 print("合并后的数据序列为:") print(c)更新棋盘二维数组信息qp=[[0 for i in range(4)] for j in range(4)] qp[1][2]=1 for i in range(4): print(qp[i])P89 例3 基于数组的车牌摇号系统功能实现from random import randint luck=[""]*20 csv_file=open("bh.csv","r") flines=csv_file.readlines() csv_file.close() i=0 for one_line in flines: tmp=one_line.strip('\n') luck[i]=tmp i=i+1 m=int(input("请输入发放数:")) c=0 while c<m: k=randint(0, 19) if luck[k]!="": c=c+1 print(luck[k]) luck[k]=""2.2链表P47 例1 基于链表实现数据合并功能from random import randint data_a=[] head_a=-1 data_b=[] head_b=-1 tmp=randint(95, 100) data_a.append([tmp,head_a]) head_a=0 for i in range(1,20): tmp=data_a[i-1][0]-randint(1, 5) data_a.append([tmp,data_a[i-1][1]]) data_a[i-1][1]=i print("链表结构的原始数据序列一") print(data_a) tmp=randint(95, 100) data_b.append([tmp,head_b]) head_b=0 for i in range(1,25): tmp=data_b[i-1][0]-randint(1, 5) data_b.append([tmp,data_b[i-1][1]]) data_b[i-1][1]=i print("链表结构的原始数据序列二") print(data_b) k_a=head_a q_a=head_a k_b=head_b while (k_a!=-1 and k_b!=-1): if data_a[k_a][0]>=data_b[k_b][0]: q_a=k_a k_a=data_a[k_a][1] else: if k_a==head_a: data_a.append([data_b[k_b][0],head_a]) head_a=len(data_a)-1 q_a=head_a k_b=data_b[k_b][1] else: data_a.append([data_b[k_b][0],k_a]) data_a[q_a][1]=len(data_a)-1 q_a=data_a[q_a][1] k_b=data_b[k_b][1] while k_b!=-1: data_a.append([data_b[k_b][0],-1]) data_a[q_a][1]=len(data_a)-1 q_a=data_a[q_a][1] k_b=data_b[k_b][1] print("链表结构合并后数据序列") print(data_a) print("按链表链接顺序输出数据序列") tmp=head_a while data_a[tmp][1]!=-1: print(data_a[tmp][0],end=" ") tmp=data_a[tmp][1] print(data_a[tmp][0])P49 例2 约瑟夫问题llist=[] n=int(input("请输入参与人数(N):")) m=int(input("请输入淘汰数(M):")) for i in range(n-1): llist.append([i+1,i+1]) llist.append([n,0]) head=0 long=n k=head i=1 while long > 1: i=i+1 if i==m: t=llist[k][1] llist[k][1]=llist[t][1] if t==head: head=llist[k][1] i=1 long=long-1 k=llist[k][1] print(llist[head][0])P50 拓展链接 链表的类实现1.自定义单向链表的节点类class LinkNode: #定义节点类LinkNode def __init__ (self,data,next_=None): #初始化节点包含两个区域self.data、self.next self.data=data #self.data区域保存数据 self.next=next_ #self.next区域保存指针2.构建单向链表class LinkList: #定义单向链表类LinkList def __init__(self): #初始化空链表 self._head=None #空链表头指针指向为空第三章 字符串、队列和栈3.1字符串P61 1.子串判断S="Hello" if ('H' in S): print("H在变量S中") else: print("H不在变量S中")for a in S: print(a,end='')2.求子串S="Hello World" print(S[6:11])3.字符串的连接S1="Wor" S2="ld" S=S1+S2 print("连接后的字符串为:",S)P63 例1 回文串s=input("请输入一个字符串:") length=len(s) mid=length//2 left=s[0:mid] temp=s[-mid:] right="" for i in range(len(temp)): right=right+temp[len(temp)-i-1] if left==right: print("Yes") else: print("No")s=input("请输入一个字符串:") s1=s[::-1] if s==s1: print("Yes") else: print("No")P64 例2 机动车违章识别系统import csv f=open("车辆号码csv","r") f_csv=csv.reader(f) k=0 for row in f_csv: #逐一枚举所有车辆信息 k=k+1 if k==1: print(row[0],"",row[1]) continue car=row[0] name=row[1] w=row[3] week="12345" pos=0 for letter in car: if letter >='A' and letter <='Z': if letter == 'B': pos=1 break if pos ==0 and w!=6 and w!=7: print(car," ",name) if pos==1: i=len(car) while i>=0: i=i-1 ch=car[i] if ch>='0' and ch<='9': break num=int(ch) if i<0: continue elif num==0: t=week[4] elif num<=5: t=week[int(ch)-1] else: t=week[9-int(ch)] if t==w: print(car," ",name) f.close()P66 拓展链接 正则表达式检查字符串中是否出现过12位数的电话号码def findphone(text): for i in range(0, len(text)): flag=True if text[i].isdecimal() and i<len(text)-12: for j in range(i+1, i+4): if not text[j].isdecimal(): #判断是否为数字 flag=False if text[i+4]!='-': flag=False for j in range(i+5, i+13): if not text[j].isdecimal(): flag=False if flag: return text[i:i+13] else: return False x=input("请输入一串字符") result=findphone(x) if result==False: print("没有找到电话号码") else: print("电话号码为:",result)使用正则表达式的写法import re phone=re.compile(r'\d\d\d\d-\d\d\d\d\d\d\d\d') x=input("请输入一串字符") mo=phone.search(x) if mo: print("电话号码为:",mo.group()) else: print("没有找到电话号码")3.2队列P71 1.建队head=0 tail=0 queue=[""]*4P71 2.入队、出队que[tail]="A" tail=tail+1 que[tail]="B" tail=tail+1 que[tail]="C" tail=tail+1 que[tail]="D" tail=tail+1 #出队 head=head+1P70 拓展链接 循环队列que=[""]*4 head=0 tail=0 que[tail]="A" tail=(tail+1)%4 que[tail]="B" tail=(tail+1)%4 que[tail]="C" tail=(tail+1)%4 que[tail]="D" tail=(tail+1)%4 print(que[head]) #元素"A"出队 head=(head+1)%4 print(que[head]) #元素"B"出队 head=(head+1)%4 print(que[head]) #元素"C"出队 head=(head+1)%4 print(que[head]) #元素"D"出队 head=(head+1)%4P73 例1 信息的加密s= input("请输入字符串:") print("加密后的串为:") que=[""]*100 head=0 tail=0 for i in range(len(s)): que[tail]=s[i] tail+=1 while head<tail: print(que[head],end="") head+=1 if head<tail: que[tail]=que[head] tail+=1 head+=1P74 银行叫号排队系统que=[-1]*1000 head=0 tail=0 print("请输入具体的操作编号:") print("1.新到顾客(取号)") print("2.下一个顾客(叫号)") print("3.程序结束") x=int(input()) while x!=3: if x==1: que[tail]=que[tail]+1 print("您当前的号码为:A%d,需要等待的人数为%d"%(tail, tail-head)) tail=tail+1 if x==2: if head==tail: print("对不起,没有等待的客户") else: print("请A%d号客户准备,马上将为您办理业务。"%head) head=head+1 x=int(input(“请输入操作\n"))3.3栈P77 1.建栈top=-1 st=[""]*4P77 2.入栈、出栈top=top+1 s[top]="A" top=top+1 s[top]="B" top=top+1 s[top]="C" top=top+1 s[top]="D" #出栈 top=top-1P79 十进制转二进制进出栈方式st=[-1]*100 top=-1 number=int(input("请输入十进制整数:")) while number >0: x=number %2 top=top+1 st[top]=x number=number//2 while top>=0: print(st[top],end="") top=top-1P80 例1 括号匹配st=[-1]*100 top=-1 flag=True s=input("请输入数学计算式:") for i in range(len(s)): if s[i]=="(": top=top+1 st[top]=s[i] elif s[i]==")": if top==-1: flag=False break else: top=top-1 if top>=0: flag=False if flag: print("括号匹配") else: print("括号不匹配")P81 拓展链接 用列表自带的函数和方法实现的栈stacklist=[] #建立一个空栈list stacklist.append("A") #字母A入栈 stacklist.append("B") #字母B入栈 print(stacklist[1]) #输出栈顶元素,为字母B print(len(stacklist)) #输出栈中元素的个数,为2 stacklist.pop() #弹出栈顶元素 print(len(stacklist)) #输出栈中元素的个数,为1,是字母A第四章 树4.1 树与二叉树4.2 二叉树的基本操作P101 实践与体验 二叉树遍历的Python程序实现class Node: def __init__(self,value=None,left=None,right=None): self.value=value self.left=left self.right=right def preTraverse(root): if root==None: return print(root.value) preTraverse(root.left) preTraverse(root.right) def midTraverse(root): if root==None: return midTraverse(root.left) print(root.value) midTraverse(root.right) def afterTraverse(root): if root==None: return afterTraverse(root.left) midTraverse(root.right) print(root.value) if __name__=='__main__': root=Node('A',Node('B',Node('D'),Node('E')),Node('C',right=Node('F',Node('G')))) print('前序遍历') preTraverse(root) print('中序遍历') midTraverse(root) print('后序遍历') afterTraverse(root)4.3 抽象数据类型第五章 数据结构与算法5.1 数据结构与算法的关系5.2 迭代与递归P119 迭代求平方根a=int(input("请输入一个需要求其平方根的数:")) x=a/2 while ((abs((x+a/x)/2-x))>0.00001): x=(x+a/x)/2 print(a,"的平方根约为",round((x+a/x)/2,6))P120 拓展链接 欧几里得算法def gcd(m,n): while n!=0: temp=n n=m%n m=temp return mP121 递归求n的阶乘def fac(n): if n==0: s=1 else: s=n*fac(n-1) return s print(fac(3))P123 例1 汉诺塔游戏def move(n, a, b, c): if(n==1): print(a, "->",c) return move(n-1, a, c, b) move(1, a, b, c) move(n-1, b, a, c) move(3,"A","B","C")* P125 实践与体验 走迷宫maze = [[0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 1, 1, 0, 1, 1, 1, 0, 1, 0], [0, 1, 1, 0, 1, 1, 1, 0, 1, 0], [0, 1, 1, 1, 1, 0, 0, 1, 1, 0], [0, 1, 0, 0, 0, 1, 1, 1, 1, 0], [0, 1, 1, 1, 0, 1, 1, 1, 1, 0], [0, 1, 0, 1, 1, 1, 0, 1, 1, 0], [0, 1, 0, 0, 0, 1, 0, 0, 1, 0], [0, 0, 1, 1, 1, 1, 1, 1, 1, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]] def valid(maze, x, y): if(x >= 0 and x < len(maze) and y >= 0 and y < len(maze[0]) and maze[x][y] == 1): return True else: return False def walk(maze, x, y): # 如果位置是迷宫的出口, if(x == 8 and y == 8): print("successful") return True if valid(maze, x, y): maze[x][y] = 2 # 做标记,防止折回 # 针对四个方向依次试探 walk(maze, x-1, y) walk(maze, x, y-1) walk(maze, x+1, y) walk(maze, x, y+1) walk(maze, 1, 1)P129 拓展链接 Python中的排序函数>>> a=[5,7,6,3,4,1,2] >>> b=sorted(a) >>> print(a) [5, 7, 6, 3, 4, 1, 2] >>> print(b) [1, 2, 3, 4, 5, 6, 7] >>> a.sort() >>> print(a) [1, 2, 3, 4, 5, 6, 7] >>> a.sort(reverse=True) >>> print(a) [7, 6, 5, 4, 3, 2, 1]P131 冒泡排序def bubble_sort(L): length=len(L) #序列长度为length,需要执行length-1遍加工 for i in range(1,length): for j in range(0, length-i): if L[j]>L[j+1]: temp=L[j] L[j]=L[j+1] L[j+1]=tempP132 例1 奥运排行榜import csv #数据读入 csvFile=open("jp.csv","r") reader=csv.reader(csvFile) a=[] for item in reader: a.append(item) csvFile.close() #排序 for i in range(1, len(a)-1): for j in range(1, len(a)-i): if int(a[j][3])<int(a[j+1][3]): temp=a[j] a[j]=a[j+1] a[j+1]=temp #数据写入 csvFile2=open('jp2.csv', 'w', newline='') writer=csv.writer(csvFile2, dialect='excel') m=len(a) for i in range(m): writer.writerow(a[i]) csvFile2.close()5.4 数据查找P136 顺序查找d=[25,22,13,18,14,11,17,19] key=18 flag=False length=len(d) for i in range(length): if d[i]==key: flag=True break if flag==True: print("查找成功!") else: print(“未找到")函数形式def seq_search(s,a): length=len(d) flag=False for i in range(length): if d[i]==key: flag=True break if flag==True: return i else: return False d=[25,22,13,18,14,11,17,19] key=15 result=seq_search(d,key) print(result)P139 二分查找规模为n的数组d中进行二分查找 key=12 d=[6,12,15,18,22,25,28,35,46,58,60] f=False #和定义子数组的边界,一开始搜索的是整个数组 i=0 j=len(d)-1 while i <= j: m=(i+j)//2 if d[m] == key: f=True b=m break if key < d[m]: j=m-1 else: i=m+1 if f==True: print("查找成功!第"+str(b)+"个") else: print("没有找到!")P139 拓展链接 二分查找算法的递归实现def bsearch(s, array): if len(array)==0: print("未找到!") return False mid=(len(array)-1)//2 if array[mid] == s: print("找到了!第"+str(mid+1)+"个") return True elif s < array[mid]: return bsearch(s, array[:mid-1]) else: return bsearch(s, array[mid+1:]) key=12 d=[6,12,15,18,22,25,28,35,46,58,60] print(bsearch(key, d))P141 例2 航空公司VIP会员积分查询import csv #数据读入 csvFlle=open("vip.csv","r") reader=csv.reader(csvFile) a=[] for item in reader: a.append(item) csvFlle.close() #排序 def bubble_sort(d): for i in range(1, len(d)-1): for j in range(1, len(d)-1): if int(d[j][0])<int(d[j+1][0]): temp=d[j] d[j]=d[j+1] d[j+1]=temp #二分查找 def bsearch(s, array): i=1 #查找范围不包含第一行数据 j=len(array)-1 while i <= j: m=(i+j)//2 if int(array[m][0]) == s: return m if s < int(array[m][0]): j=m-1 else: i=m+1 return -1 #未找到返回-1 bubble_sort(a) key = int(input('请输入要查询的VP号:')) m=bsearch(key, a) if m!=-1: print(a[m][1],"先生/女士,您的积分为:",a[m][3]) else: print('找不到VP号对应的用户信息!')第六章 大数据时代数据的组织6.1 实时查询系统中数据的组织6.2 POI数据的组织与应
2024年04月11日
7 阅读
0 评论
0 点赞
2024-04-11
高中信息技术(Python) 必修2 信息系统与社会 源代码
第一章 信息系统概述1.1 信息技术与信息系统1.2 信息系统的组成与功能1.3 信息系统的应用1.4 信息社会及其发展第二章 信息系统的支撑技术2.1 计算机硬件2.2 计算机软件2.3 移动终端2.4 传感与控制P58 microbit 获取环境温度from microbit import * while True: print(temperature()) sleep(200)P59 microbit 通过串口调试查看串口数据import serial ser = serial.Serial() #设置通讯波特率,需要与micro:bit中设定的通讯速率一致 ser.baudrate = 115200 #设置串口号 ser.port = 'COM3' ser.open() while True: print(ser.readline())P60 microbit 将得到的串口数据保存到文本文件import serial ser = serial.Serial() ser.baudrate = 115200 ser.port = 'COM3' ser.open() f=open('microbit.txt', 'wb') a=20 while a>0: a-=1 line=ser.readline() print(line) f.write(line) f.close() ser.close()* P65 实践与体验 用计算机控制micro:bit的LED阵列microbit烧录程序from microbit import * while True: if uart.any(): incoming = str(uart.readall(), "UTF-8") incoming=incoming.strip('\n') if incoming=='H': display.show(Image.HAPPY) print("I am happy") elif incoming=='S': display.show(Image.SAD) print("I am sad") else: print("err")通过串口用Python程序控制microbit的LED阵列import serial ser = serial.Serial() ser.baudrate = 115200 ser.port = 'COM3' ser.open()有规律地切换表情import serial,time ser = serial.Serial() ser.baudrate = 115200 ser.port = 'COM3' ser.open() while True: time.sleep(1) ser.write('H'.encode()) time.sleep(1) ser.write('S'.encode())shell内交互控制LED阵列import serial,time ser = serial.Serial() ser.baudrate = 115200 ser.port = 'COM3' ser.open() while True: name=input() ser.write(name.encode()) line = ser.readline() print(line.strip().decode())2.5 网络系统2.6 网络应用软件开发安装网络应用涉及的模块可以将如下代码复制到shell中执行安装,将其保存为.bat可以一键安装pip install Flask==1.0.2 -i https://pypi.tuna.tsinghua.edu.cn/simple pip install Flask-Script==2.0.6 -i https://pypi.tuna.tsinghua.edu.cn/simple pip install Flask-Bootstrap==3.3.7.1 -i https://pypi.tuna.tsinghua.edu.cn/simple pip install Flask-Moment==0.6.0 -i https://pypi.tuna.tsinghua.edu.cn/simple pip install WTForms==2.2.1 -i https://pypi.tuna.tsinghua.edu.cn/simple pip install Werkzeug==0.16.0 -i https://pypi.tuna.tsinghua.edu.cn/simple pip install Flask-WTF==0.14.2 -i https://pypi.tuna.tsinghua.edu.cn/simple pip install Flask-SQLAlchemy==2.3.2 -i https://pypi.tuna.tsinghua.edu.cn/simple pip install SQLAlchemy==1.3.17 -i https://pypi.tuna.tsinghua.edu.cn/simpleP86 例1 用Flask Web框架实现一个在网页中显示文本“这是我的第一个网页程序!”的web应用from flask import Flask from flask_script import Server,Manager app = Flask(__name__) manager = Manager(app) server = Server(host="0.0.0.0",port=80,threaded=True) manager.add_command("runserver",server) @app.route('/') def index(): return '这是我的第一个网页程序!' if __name__ == '__main__': manager.run()P87 例2 使用FlaskForm模块实现网络聊天机器人简单对话的功能 webrobot.pyfrom flask import Flask, render_template from flask_script import Server, Manager from flask_bootstrap import Bootstrap from flask_moment import Moment from flask_wtf import FlaskForm from wtforms import StringField, SubmitField from wtforms.validators import Required import sys sys.path.insert(0, "../") import aiml k = aiml.Kernel() k.learn("cn-startup.xml") k.respond("load aiml cn") k.respond("start") app = Flask(__name__) app.config['SECRET_KEY'] = 'hard to guess string' manager = Manager(app) server = Server(host="127.0.0.1", port=80, threaded=True) manager.add_command("runserver", server) bootstrap = Bootstrap(app) moment = Moment(app) class NameForm(FlaskForm): name = StringField('请开始交谈:', validators=[Required()]) submit = SubmitField('提交') @app.route('/', methods=['GET', 'POST']) def index(): name = '' form = NameForm() if form.validate_on_submit(): name = form.name.data form.name.data = '' return render_template('index.html', form=form, name=k.respond(name)) if __name__ == '__main__': manager.run()全部打包代码,已设置bat,支持一键运行* P84 实践与体验 为聊天机器人增加聊天记录1.创建数据表CREATE TABLE "tlkTxt" ( "id" INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, "own" INTEGER, "txt" TEXT );网络聊天机器人.zip第三章 信息系统安全3.1 信息安全与保护3.2 信息系统安全与防护P113 凯撒密码算法的程序实现原代码在边界字符会出错,以下为笔者修改后的代码def change(code,key): if 'a'<=code<='z': t=ord(code)-ord('a')+key return chr((t+26)%26+ord('a')) if 'A'<=code<='Z': t=ord(code)-ord('A')+key return chr((t+26)%26+ord('A')) return code def encrypt(code,key): code_new ="" for s in code: code_new += change(s,key) print(code_new) return code_new def decrypt(code,key): code_new ="" for s in code: code_new +=change(s,-key) print(code_new) return code_new def main(): print("请选择数字1或2:") print("1:加密") print("2:解密") select = input() if select == "1": code = input("请输入加密字符串:") key = int(input("请输入偏移位数:")) encrypt(code,key) elif select == "2": code = input("请输入解密字符串:") key = int(input("请输入偏移位数:")) decrypt(code,key) else: print("输入错误,请重试!") if __name__ == '__main__': main()第四章 信息系统4.1 搭建信息系统的前期准备4.2 搭建信息系统P143 拓展链接 在Python中使用SQLite数据库# 连接SQLite数据库 coon=sqlite3.connect('test.db') #创建SQLite表sql语句 create table students(name text, area txt, id int) # 插入记录sql语句 insert into students(name, area, id) values(‘Lisi','Hangzhou',18) # 查询记录(select)、删除记录(delete)、更新记录(update)P145 室内环境实时监测系统 Web服务器代码# coding= UTF-8 import sqlite3 import datetime import json from flask import Flask,render_template, request DATABASE = 'data/data.db' app = Flask(__name__) @app.route("/") def hello(): db = sqlite3.connect(DATABASE) cur = db.cursor() cur.execute("SELECT * FROM sensorlog WHERE sensorid =1") data = cur.fetchall() cur.close() db.close() temp1 = data[len(data) - 1] temp=temp1[2] return render_template('vews.html', data=data,temp=temp) #Get data @app.route("/get",methods=['GET']) def get_data(): sensorid=int(request.args.get('id')) db = sqlite3.connect(DATABASE) cur = db.cursor() cur.execute("SELECT * FROM sensorlog WHERE sensorid = %s"% sensorid) data = cur.fetchall() dbsum=len(data) dset= temp=[] for i in range(dbsum): value= value['sensorvalue']=data[i][2] value['updatetime']=data[i][3] temp.append(value) #dset['value']= dset['value']=temp djson=json.dumps(dset) return djson #Adding data @app.route("/input",methods=['POST','GET']) def add_data(): if request.method == 'POST': sensorid = int(request.form.get('id')) sensorvalue = float(request.form.get('val')) else: sensorid = int(request.args.get('id')) sensorvalue = float(request.args.get('val')) nowtime = datetime.datetime.now() nowtime = nowtime.strftime('%Y-%m-%d %H:%M:%S') db = sqlite3.connect(DATABASE) cur = db.cursor() cur.execute("INSERT INTO sensorlog(sensorid,sensorvalue,updatetime) VALUES(%d,%f,'%s')" %(sensorid,sensorvalue,nowtime) ) db.commit() cur.execute("SELECT * FROM sensorlist where sensorid = %d"% sensorid) rv = cur.fetchall() cur.close() db.close() maxrv = rv[0][2] minrv = rv[0][3] if sensorvalue > maxrv or sensorvalue < minrv: return '1' else: return '0' if __name__ == "__main__": # 删掉debug=True,threaded=True IDLE里可以运行 app.run(host="0.0.0.0", port=8080,debug=True,threaded=True)P146 室内环境实时监测系统 Web模版文件代码<!doctype html> <body><meta http-equiv="refresh" content="60"></body> <style> #center{ MARGIN-RIGHT: auto;MARGIN-LEFT: auto;background:#eff7ff;width:600px; height:500px;vertical-align:left;overflow-y:scroll; overflow-x:scroll} </style> <title>室内环境监测系统</title> <h1 align="center">室内环境监测系统</h1> <h2 align="center">当前室内温度:} </h2> <h2 align="center"><a href="/">刷新</a>历史数据列表:</h2> <div id="center" style="border:2px solid #96c2f1"> 温度 记录时间<br> } } <br> </div>P146 室内环境实时监测系统 智能终端程序from microbit import * import Obloq IP="192.168.0.101" PORT="8080" SSID="jf" PASSWORD="pkq8888" uart.init(baudrate=115200, bits=8, parity=None, stop=1, tx=pin2, rx=pin1) while Obloq.connectWifi(SSID,PASSWORD,10000) != True: display.show(".") display.scroll(Obloq.ifconfig()) Obloq.httpSet(IP,PORT) while True: errno,resp=Obloq.get("input?id=1&val="+str(temperature()),10000) if errno == 200: display.scroll(resp) else: display.scroll(str(errno)) sleep(1000*5)Myweather1.3.1.zip4.3 完善信息系统
2024年04月11日
9 阅读
0 评论
0 点赞
2024-03-28
Android 禁止系统进入深度休眠
在Linux系统中,wake_lock是一直锁机制,只要有驱动占用这个锁,系统就不会进入深度休眠。获取此锁的方法有两种:1、在adb中通过指令获取wake_lock,系统就不会进入深度休眠echo "PowerManagerService.noSuspend" > /sys/power/wake_lock2、在驱动文件中获取wake_lock(1)添加头文件# include <linux/wakelock.h>(2)定义 wake_lock 结构体static struct wake_lock wake_lock_always(3)在 xxx_init 函数中初始化锁wake_lock_init(&wake_lock_always, WAKE_LOCK_SUSPEND, "wake_lock_always");(4)在 xxx_suspend 函数中获取锁wake_lock(&wake_lock_always);(5)在 xxx_resume 函数中释放锁wake_unlock(&wake_lock_always);
2024年03月28日
7 阅读
0 评论
0 点赞
2023-10-31
设置 ubuntu 中各种应用的代理
1、设置环境变量http_proxy和https_proxy下面命令设置环境变量http_proxy和https_proxy为http://127.0.0.1:7890,分别用于访问非加密和加密网址。目前大部分网址都是加密网址。export http_proxy=http://127.0.0.1:7890export https_proxy=http://127.0.0.1:7890该命令对当前窗口有效。要想自动设置,需要添加在启动脚本~/.zshrc或者~/.bashrc(取决于你用哪一种 sh ),对当前用户所有新开的窗口有效。也可以放入/etc/profile,将对所有用户的所有新开窗口生效。这两个环境变量对下面应用有效:apt。单独设置请见后文。pip。单独设置请见后文。git。该命令也可以自定义代理。curl。也可以curl -x http://127.0.0.1:7890 url直接指定代理。wget。单独设置请见后文。2、设置 APT 代理在/etc/apt/apt.conf里添加下面两行:Acquire::http::proxy "http://127.0.0.1:7890/";Acquire::https::proxy "http://127.0.0.1:7890/";3、设置 NPM 代理根据 npm 源registry地址,设置下面两个之一(最好两个都设置上):npm config set proxy=http://127.0.0.1:7890npm config set https-proxy http://127.0.0.1:7890取消设置代理:npm config delete proxynpm config delete https-proxy4、设置 PIP 代理可以直接在命令行里指定代理:pip install mkdocs --proxy=http://127.0.0.1:7890也可以放入配置文件~/pip/pip.conf,添加内容:[global]proxy = http://127.0.0.1:78905、设置 wget 代理可以直接指定代理:wget -e "http_proxy=http://127.0.0.1:7890" 或者编辑~/.wgetrc` 文件,添加以下内容:use_proxy = onhttp_proxy = http_proxy=http://127.0.0.1:7890https_proxy = http_proxy=http://127.0.0.1:7890ftp_proxy = http_proxy=http://127.0.0.1:7890
2023年10月31日
9 阅读
0 评论
0 点赞
1
2
...
4