Python学习(一)

发布时间:2024-11-21 20:40

学习Python基础语法:https://www.runoob.com/python/python-tutorial.html #生活技巧# #工作学习技巧# #编程学习资源#

目录

一、简单程序(from Python 编程快速上手)

1.1、利用pip安装第三方模块pyperclip剪贴板模块.

1.2、利用分离文本中的行,并添加星号

1.3、更改文件名

1.4、使用日志模块可以调整打印等级

1.5、从web获取信息

1.5.1Beautiful Soup模块

1.5.2、selenium模块

1.6、openpyxl模块可以导入用来处理EXcel电子表格

1.6.1 解析Excel电子表格中的信息

1.6.2 从txt中读入数据到EXCEL中去

1.6.3 合并文件GUI

1.7、控制鼠标

1.8、对比图片

二、Python核心编程

2.1 正则表达式

2.2 客户端和服务器端

2.3 Python的多线程模块优先使用threading模块,而不是thread模块。下面是使用jupyter notebook 编写的程序

2.4 偏函数

2.5 lambda函数

2.6 数据库相关

2.7microsoft office 编程

三、相关工程技术

3.1 pyinstaller 安装打包EXE程序

3.2 python调用c语言函数

一、简单程序(from Python 编程快速上手)

1.1、利用pip安装第三方模块pyperclip剪贴板模块.

PASSWORDS = {'email': '111',

'blog': '222',

'luggage': '333'}

import pyperclip, sys

if len(sys.argv) < 2:

print('zyl')

sys.exit()

account = sys.argv[1]

if account in PASSWORDS:

pyperclip.copy(PASSWORDS[account])

print('zzz ' + account + ' yyy.')

else:

print('lll ' + account)

1.2、利用分离文本中的行,并添加星号

import pyperclip, sys

text = pyperclip.paste()

lines = text.split('\n')

for i in range(len(lines)):

lines[i] = '*' + lines[i]

print(lines)

text = '\n'.join(lines)

pyperclip.copy(text)

利用剪贴板程序和正则表达式替换文本

第一、写正则表达式的规则;

第二、写需要替换的单词.sub;

第三、拷贝粘贴。

下面的例子是寻找美国的电话号码和邮箱地址。

import pyperclip, re

phone = re.compile(r'''(

(\d{3}|\(\d{3}\))? #area code

(\s|-|\.)? #separator

(\d{3}) #first 3 digits

(\s|-|\.) #separator

(\d{4}) #first 4 digits

(\s*(ext|x|ext\.)\s*(\d{2,5}))? #extension

)''', re.VERBOSE)

email = re.compile(r'''(

[a-zA-Z0-9._%+-]+ #usrname

@ #@ symbol

[a-zA-Z0-9.-]+ #domain name

(\.[a-zA-Z]{2,4}) #dot-something

)''', re.VERBOSE)

text = str(pyperclip.paste())

matches = []

for groups in phone.findall(text):

phoneNum = '-'.join([groups[1], groups[3], groups[5]])

if groups[8] != '':

phoneNum += ' x' + groups[8]

matches.append(phoneNum)

for groups in email.findall(text):

matches.append(groups[0])

if len(matches) > 0:

pyperclip.copy('\n'.join(matches))

print('\n'.join(matches))

else:

print('NO')

1.3、更改文件名

os和shutil模块可以提供一些函数,用于复制、移动、改名和删除文件。如果怕误删文件,可以用模块send2trash.zipfile模块是用来压缩和解压缩文件的。

import shutil, os, re

datePattern = re.compile(r"""^(.*?) #all text before the date

    ((0|1)?\d)-                     #one or two digits for the month

    ((0|1|2|3)?\d)-                 #one or two digits for the day

    ((19|20)\d\d)                   #for digits for the year

    (.*?)$                          #all text after the date

    """, re.VERBOSE)

for amerFilename in os.listdir('.'):

    mo = datePattern.search(amerFilename)

if mo == None:

continue

    beforePart = mo.group(1)

    monthPart = mo.group(2)

    dayPart = mo.group(4)

    yearPart = mo.group(6)

    afterPart = mo.group(8)

    euroFilename = beforePart + dayPart + '-' + monthPart + '-' + yearPart + afterPart

    absWorkingDir = os.path.abspath('.')

    amerFilename = os.path.join(absWorkingDir, amerFilename)

    euroFilename = os.path.join(absWorkingDir, euroFilename)

print('"%s" to "%s"' % (amerFilename, euroFilename))

    shutil.move(amerFilename, euroFilename)

正则表达式模式\s\s+表示至少拥有两个以上的空白符。

1.4、使用日志模块可以调整打印等级

logging模块引入。分等级为DEBUG、INFO、WARNING、ERROR、CRITICAL。

basicConfig()的level参数可以设置默认调试等级。

logging.disable传入一个日志级别,它就会禁止该级别和更低级别的所有日志消息。

1.5、从web获取信息

1.5.1Beautiful Soup模块

webbrowser:是Python自带的,打开浏览器获取指定页面

requests:从因特网上下载文件和网页

Beautiful Soup:解析HTML,即网页编写格式

import webbrowser, sys, pyperclip

if len(sys.argv) >1:

address = ' '.join(sys.argv[1:])

else:

address = pyperclip.paste()

webbrowser.open('http://www.google.cn/maps/place/' + address)

在查找网页上的图片或者文字时,需要查看该网页的源码。同时按键F12查看调试窗口可以通过右击“审查元素”来查看该文字或者图片在哪个节点上。

然后通过BeautifulSoup中的函数“节点”去不断的循环查询。

import webbrowser, sys, bs4, requests

print('百度...')

res = requests.get('https://www.baidu.com/s?ie=utf-8&wd=' + ' '.join('sss'))

res.raise_for_status()

playFile = open('zyl.txt', 'wb')

for chunk in res.iter_content(10000):

playFile.write(chunk)

playFile.close()

soup = bs4.BeautifulSoup(res.text, 'html)

linkElems = soup.select('.r a', "html.parser")

numOpen = min(5, len(linkElems))

print('百度...')

for i in range(numOpen):

print('百度...')

webbrowser.open('https://www.baidu.com' + linkElems[i].get('href'))

import os, bs4, requests

url = 'https://xkcd.com'

os.makedirs('xkcd', exist_ok = True)

while not url.endswith('#'):

print('下载中 %s...' % url)

res = requests.get(url)

res.raise_for_status()

soup = bs4.BeautifulSoup(res.text, "html.parser")

comicElem = soup.select('#comic img')

if comicElem == []:

print('不能找到图片!')

else:

comicUrl = 'http:' + comicElem[0].get('src')

print('开始下载图片 %s' % (comicUrl))

res = requests.get(comicUrl)

res.raise_for_status()

imageFile = open(os.path.join('xkcd', os.path.basename(comicUrl)), 'wb')

for chunk in res.iter_content(100000):

imageFile.write(chunk)

imageFile.close()

prevLink = soup.select('a[rel="prev"]')[0]

url = 'http://xkcd.com' + prevLink.get('href')

print('完成')

1.5.2、selenium模块

selenium:启动并控制一个web浏览器。selenium能够填写表单,并模拟鼠标在这个浏览器中点击。主要地Chrome,Safari,Firefox  浏览器。

自动打开Google浏览器需要安装的插件:参考目录:https://www.2cto.com/kf/201704/622848.html。

from selenium import webdriver

path = "C:\Program Files (x86)\Google\Chrome\Application\chromedriver\chromedriver.exe"

driver = webdriver.Chrome(executable_path=path)

driver.get('https://mail.163.com')

1.6、openpyxl模块可以导入用来处理EXcel电子表格

1.6.1 解析Excel电子表格中的信息

加载电子表格文件,准备一些变量或者数据结构,然后循环遍历电子表格中的每一行。

import openpyxl

wb = openpyxl.load_workbook('zyl.xlsx')

sheet = wb['Sheet1']

UPDATE_TAGS = {'z':1.2,

'y':1.3,

'l':1.4}

for rowNum in range(1, 1+sheet.max_row):

tagName = sheet.cell(row=rowNum, column=1).value

print(tagName, sheet.max_row)

if tagName in UPDATE_TAGS:

sheet.cell(row=rowNum, column=2).value = UPDATE_TAGS[tagName]

wb.save('update_zyl.xlsx')

import openpyxl

wb = openpyxl.load_workbook('zyl.xlsx')

sheet = wb['Sheet1']

file = open('zyl.c', 'w')

mo = "//第一行\n"

for rowNum in range(1, sheet.max_row):

AD = sheet.cell(row=rowNum+1, column=2).value

AD1 = sheet.cell(row=rowNum+1, column=3).value

AD2 = sheet.cell(row=rowNum+1, column=4).value

AD3 = sheet.cell(row=rowNum+1, column=5).value

print(rowNum, sheet.max_row)

print(AD, AD1, AD2, AD3)

make = "((make(" + str(AD) + ", DA)," + str(AD1) + ", " + str(AD2) + ", "+ str(AD3) + ")\n"

file.write(mo)

file.write(make)

file.close()

  可以通过openpyxl.styles模块导入Font()和Style()函数来设置单元格的字体风格。此外也可以用公式等Excel中的许多操作。

1.6.2 从txt中读入数据到EXCEL中去

import openpyxl

import os

print(os.getcwd())

os.chdir("D:\study\PythonStudy")

txtName = r"value.txt"

wb = openpyxl.load_workbook('value.xlsx')

sheet = wb['Sheet1']

fp = open(txtName)

rowNum = 1

for line in fp.readlines():

print(line)

a = line.split(":")[0]

b = int(line.split(":")[1])

sheet.cell(row=rowNum, column=1).value = a

sheet.cell(row=rowNum, column=2).value = b

print("a = %s b = %d" % (a, b))

rowNum += 1

wb.save('update_value.xlsx')

fp.close()

    Python可以直接读入.csv和Jason数据,然后进行分析。它们都是常见的文本格式,用于保存数据。经常用作简单的电子表格或者网络应用程序的数据。

1.6.3 合并文件GUI

import os

import tkinter as tk

from tkinter import filedialog

from tkinter import scrolledtext

app_name = ".\\sensor.app"

fpga_name = ".\\sensor.fpga"

pack_magic = "123456789"

def openfiles2():

global app_name

app_name = filedialog.askopenfilename(title='open APP file', filetypes=[('app', '*.app'), ('All Files', '*')])

def openfilecgns():

global fpga_name

fpga_name = filedialog.askopenfilename(title='open FPGA file', filetypes=[('fpga', '*.fpga'), ('All Files', '*')])

def zip_files():

files = [app_name, fpga_name]

pwd = os.path.basename(app_name)

zip_name = pwd.split('.', 1 )[0] + ".zyl"

zip = open(zip_name, mode="w+")

zip.write(pack_magic)

try:

for file in files:

Information_Window.insert("end", "Packing: " + file + "\n")

Information_Window.see("end")

compress_fp = open(file, mode="r")

for line in compress_fp.readlines():

zip.write(line)

compress_fp.close()

except IOError:

error = "pack "+zip_name+" fail!"

else:

error = "pack "+zip_name+" success!"

zip.close()

Information_Window.insert("end", "Packing result:" + "\n"+ error + "\n\n")

Information_Window.see("end")

GUI = tk.Tk()

GUI.title("Pack Tool")

GUI.geometry("600x380")

Information = tk.LabelFrame(GUI, text="Operate Information", padx=10, pady=10)

Information.place(x=200, y=0)

Information_Window = scrolledtext.ScrolledText(Information, width=50, height=20, wrap = tk.WORD)

Information_Window.grid()

btn1 = tk.Button(GUI, text='open APP file', font=("Times New Roman", 15, 'bold'), width=15, height=1, command=openfiles2)

btn2 = tk.Button(GUI, text='open FPGA file', font=('Times New Roman', 15, 'bold'), width=15, height=1, command=openfilecgns)

btn3 = tk.Button(GUI, text='begin pack', font=('Times New Roman', 15, 'bold'), width=15, height=1, command=zip_files)

btn1.place(x=0,y=0)

btn2.place(x=0,y=50)

btn3.place(x=0,y=100)

GUI.mainloop()

如果想改成二进制的读写文件需要做以下操作,引入struct模块。

data = struct.pack("i", pack_magic)

zip.write(data)

参考网址:

https://blog.csdn.net/cxrlalala/article/details/80633786

https://www.cnblogs.com/anloveslife/p/7532686.html

http://www.cnblogs.com/pipihaoke/p/8033844.html

1.7、控制鼠标

import pyautogui

print("按Ctrl + c 退出")

try:

while True:

x, y = pyautogui.position()

positionStr = "X: " + str(x).rjust(4) + "Y: " + str(y).rjust(4)

print(positionStr, end='')

print('\b' * len(positionStr), end='', flush=True)

except KeyboardInterrupt:

print("\n完成。")

控制鼠标隔五秒点击的写法:

time.sleep(10)

pyautogui.click(941, 34, button='left')

1.8、对比图片

import os

from PIL import Image

from PIL import ImageChops

def compare_images(path_one, path_two, diff_save_location):

"""

比较图片,如果有不同则生成展示不同的图片

@参数一: path_one: 第一张图片的路径

@参数二: path_two: 第二张图片的路径

@参数三: diff_save_location: 不同图的保存路径

"""

image_one = Image.open(path_one)

image_two = Image.open(path_two)

diff = ImageChops.difference(image_one, image_two)

if diff.getbbox() is None:

return

else:

diff.save(diff_save_location)

if __name__ == '__main__':

pwd = os.getcwd()

print(pwd)

compare_images('.\\picture\\1.png',

'.\\picture\\2.png',

'.\\picture\\不同.jpg')

二、Python核心编程

2.1 正则表达式

正则表达式中的搜索和匹配是不一样的。match匹配的单个字符串(seafood,返回失败,但是 sea food,返回成功),search搜索的是字符串中是否有该字符模式(seafood返回成功)

2.2 客户端和服务器端

服务器端 时间服务器

from socket import *

from time import ctime

HOST = ''

PORT = 21567

BUFSIZ = 1024

ADDR = (HOST, PORT)

tcpSerSock = socket(AF_INET, SOCK_STREAM)

tcpSerSock.bind(ADDR)

tcpSerSock.listen(5)

while True:

print('等待被链接。。。')

    tcpCliSock, addr = tcpSerSock.accept()

print('。。。链接来自:', addr)

while True:

        data = tcpCliSock.recv(BUFSIZ).decode()

if not data:

break

        tcpCliSock.send(('[%s] %s' % (bytes(ctime(), 'utf-8'), data)).encode())

    tcpCliSock.close()

tcpSerSock.close()

客户端

from socket import *

HOST = '127.0.0.1'

PORT = 21567

BUFSIZ = 1024

ADDR = (HOST, PORT)

tcpCliSock = socket(AF_INET, SOCK_STREAM)

tcpCliSock.connect(ADDR)

while True:

data = input('> ')

if not data:

break

tcpCliSock.send(data.encode())

data = tcpCliSock.recv(BUFSIZ)

if not data:

break

print(data.decode('utf-8'))

tcpCliSock.close()

2.3 Python的多线程模块优先使用threading模块,而不是thread模块。下面是使用jupyter notebook 编写的程序

import _thread

from time import sleep, ctime

def loop0():

print("start loop 0 at: %s" % (ctime()))

sleep(4)

print("loop 0 done at: %s" % (ctime()))

def loop1():

print("start loop 1 at: %s" % (ctime()))

sleep(2)

print("loop 1 done at: %s" % (ctime()))

def main():

print("starting at: %s" % (ctime()))

_thread.start_new_thread(loop0, ())

_thread.start_new_thread(loop1, ())

sleep(6)

print("all DONE at: %s" % (ctime()))

if __name__ == '__main__':

main()

'

守护线程一般是一个等待客户端请求服务的服务器。如果没有客户端的请求,守护线程就是空闲的。如果把一个线程设置为守护线程,就表示这个线程是不重要的,线程退出时不需要等待这个线程执行完毕。

在亚马逊查询书本排行

from concurrent.futures import ThreadPoolExecutor

from re import compile

from time import ctime

from urllib.request import urlopen as uopen

REGEX = compile(b'#([\d,]+) in Books ')

AMZN = 'https://www.amazon.com/dp/'

ISBNs = {

'0132678209': 'Core Python Programing',

}

def getRanking(isbn):

with uopen('{0}{1}'.format(AMZN, isbn)) as page:

return str(REGEX.findall(page.read())[0], 'utf-8')

def main():

print('at', ctime(), 'on Amzon...')

with ThreadPoolExecutor(1) as executor:

for isbn, ranking in zip(

ISBNs, executor.map(getRanking, ISBNs)):

print('- %r ranked %s' % (ISBNs[isbn], ranking))

print('all done at:', ctime())

if __name__ == '__main__':

main()

2.4 偏函数

1、对于有很多可调用对象,并且许多调用都反复使用相同参数的情况,使用偏函数比较合适。

2、偏函数是2.5版本以后引进来的东西。属于函数式编程的一部分,使用偏函数可以通过有效地“冻结”那些预先确定的参数,来缓存函数参数,然后在运行时,当获得需要的剩余参数后,可以将他们解冻,传递到最终的参数中,从而使用最终确定的所有参数去调用函数。

from functools import partial as pto

def add(a,b):

return a+b

puls = pto(add,9)

result = puls(6)

print(result)

result = puls(1)

print(result)

'

参考地址:https://blog.csdn.net/tongjinrui/article/details/70800370

2.5 lambda函数

一、lambda函数也叫匿名函数,即,函数没有具体的名称。先来看一个最简单例子:

def f(x):
return x**2
print f(4)

Python中使用lambda的话,写成这样

g = lambda x : x**2
print g(4)

二、lambda和普通的函数相比,就是省去了函数名称而已,同时这样的匿名函数,又不能共享在别的地方调用。

其实说的没错,lambda在Python这种动态的语言中确实没有起到什么惊天动地的作用,因为有很多别的方法能够代替lambda。

1. 使用Python写一些执行脚本时,使用lambda可以省去定义函数的过程,让代码更加精简。

2. 对于一些抽象的,不会别的地方再复用的函数,有时候给函数起个名字也是个难题,使用lambda不需要考虑命名的问题。

3. 使用lambda在某些时候让代码更容易理解。

三、其他高阶函数

map和reduce,可以用的时候试试看。

参考地址:https://blog.csdn.net/yezonggang/article/details/50978114

2.6 数据库相关

小型的数据库管理,可以先安装个sqlite创建个数据库DB,然后利用Python适配器去连接,连接后可以创建表等操作。

2.7microsoft office 编程

需要安装win32com,可以直接利用pip install安装合适的版本,手动安装到的版本可能会不对。

win32com会出现窗口的操作。

from tkinter import Tk

from time import sleep

from tkinter import messagebox

import win32com.client as win32

warn = lambda app:messagebox.askokcancel(app,'Exit?')

RANGE = range(3,8)

def excel():

app='Excel'

xl=win32.gencache.EnsureDispatch('%s.Application' % app)

ss=xl.Workbooks.Add()

sh=ss.ActiveSheet

xl.Visible=True

sleep(1)

sh.Cells(1,1).Value='Python-to-%s Demo' % app

sleep(1)

for i in RANGE:

sh.Cells(i,1).Value='Line %d' %1

sleep(1)

sh.Cells(i+2,1).Value="Th-th-th-that's all flocs!"

warn(app)

ss.Close(False)

xl.Application.Quit()

if __name__=='__main__':

Tk().withdraw()

excel()

三、相关工程技术

3.1 pyinstaller 安装打包EXE程序

1、首先利用pip install pyinstaller,当然也可以在官网下载安装包利用Python自己安装

2、打包的方法,既可以利用安装好的pyinstaller.exe 直接运行安装。

pyinstaller.exe -F -c hello.py的路径在安装,C:\Users\Administrator\AppData\Local\Programs\Python\Python37\Scripts

也可以,利用在官网下载的pyinstaller后,python pyinstaller.py -F -c hello.py的方式安装,其中的参数

-F 表示生成单个可执行文件

-w 表示去掉控制台窗口,这在GUI界面时非常有用。不过如果是命令行程序的话那就把这个选项删除吧!

-p 表示你自己自定义需要加载的类路径,一般情况下用不到

-i 表示可执行文件的图标

-c 表示生成控制台的方式

3.2 python调用c语言函数

1、用ctypes的动态库实现的一种方法,下面是Linux下实现的一种方法

参考地址: https://blog.csdn.net/jiuzuidongpo/article/details/43982057

2、按照Python C-API的编程规范,用C编写底层实现函数。

用Python自带的disutils模块来管理编译、打包、生成Python模块。

参考地址:https://www.jianshu.com/p/cd28e8b0cce1

网址:Python学习(一) https://www.yuejiaxmz.com/news/view/179675

相关内容

python学习旅程笔记2
Python学习笔记——参数axis=0,1,2...
生活中的5 个自动化Python 项目——从初学者到高级(附零基础学习教程)
Python深度学习实践:深度学习在虚拟助理中的应用
使用Python实现深度学习模型:智能家电控制与优化
python
python 学习笔记24 图片视频修复
一款Python实用神器,5 行 Python 代码 实现一键批量扣图
5 个自动化生活的 Python 项目:从初学者到高级
pyenv =》python 版本和python 开发工作环境管理神器下载

随便看看