20个硬核Python脚本

2024-05-09 17:28
文章标签 硬核 20 python 脚本

本文主要是介绍20个硬核Python脚本,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

整理了一个覆盖面比较广泛的Python脚本示例,涉及到机器学习、数据处理、还有算法er可能会遇到自己写后台的一些案例。

另外,每个模块底部提供了对于官网文档,更加方便的查询具体的使用方法。

内容由简到难,如果对你有帮助的话希望点赞 收藏    谢谢。

1、Hello World

print("Hello, World!")

官方文档: https://docs.python.org/3/

2、变量和数据类型

name = "Alice"
age = 30
height = 175.5
is_student = True

官方文档: https://docs.python.org/3/tutorial/introduction.html#numbers

3、列表

fruits = ["apple", "banana", "cherry"]
fruits.append("date")
print(fruits)

官方文档: https://docs.python.org/3/tutorial/introduction.html#lists

4、字典

person = {"name": "Alice", "age": 30, "city": "New York"}
print(person["name"])

5、循环

for i in range(1, 6):print(i)

官方文档: https://docs.python.org/3/tutorial/introduction.html#first-steps-towards-programming

6、条件语句

x = 5
if x > 10:print("x is greater than 10")
else:print("x is not greater than 10")

官方文档: https://docs.python.org/3/tutorial/controlflow.html

7、函数

def greet(name):return f"Hello, {name}!"message = greet("Alice")
print(message)

官方文档: https://docs.python.org/3/tutorial/controlflow.html#defining-functions

8、模块导入

import mathprint(math.sqrt(16))

官方文档: https://docs.python.org/3/tutorial/modules.html

9、异常处理

try:result = 10 / 0
except ZeroDivisionError:print("Division by zero is not allowed.")

官方文档: https://docs.python.org/3/tutorial/errors.html

10、文件操作

with open("example.txt", "w") as file:file.write("Hello, File!")with open("example.txt", "r") as file:content = file.read()print(content)

官方文档: https://docs.python.org/3/tutorial/inputoutput.html

11、日期和时间

from datetime import datetimenow = datetime.now()
print(now)

官方文档: https://docs.python.org/3/library/datetime.html

12、随机数生成

import randomrandom_number = random.randint(1, 100)
print(random_number)

13、正则表达式

import retext = "Hello, 12345"
pattern = r'\d+'
match = re.search(pattern, text)
if match:print(match.group())

官方文档: https://docs.python.org/3/library/re.html

14、Web请求

import requestsresponse = requests.get("https://www.example.com")
print(response.text)

官方文档: https://docs.python-requests.org/en/master/

15、CSV文件处理

import csvwith open("data.csv", "w", newline="") as file:writer = csv.writer(file)writer.writerow(["Name", "Age"])writer.writerow(["Alice", 25])with open("data.csv", "r") as file:reader = csv.reader(file)for row in reader:print(row)

官方文档: https://docs.python.org/3/library/csv.html

16、JSON处理

import jsondata = {"name": "Bob", "age": 35}
json_data = json.dumps(data)
print(json_data)

官方文档: https://docs.python.org/3/library/json.html

17、爬虫 - BeautifulSoup

from bs4 import BeautifulSoup
import requestsurl = "https://www.example.com"
response = requests.get(url)
soup = BeautifulSoup(response.text, "html.parser")
print(soup.title.text)

官方文档: https://www.crummy.com/software/BeautifulSoup/bs4/doc/

18、多线程

import threadingdef print_numbers():for i in range(1, 6):print(f"Number: {i}")def print_letters():for letter in "abcde":print(f"Letter: {letter}")thread1 = threading.Thread(target=print_numbers)
thread2 = threading.Thread(target=print_letters)thread1.start()
thread2.start()

官方文档: https://docs.python.org/3/library/threading.html

19、数据爬取 - Selenium

from selenium import webdriverdriver = webdriver.Chrome()
driver.get("https://www.example.com")

官方文档: https://www.selenium.dev/documentation/en/

20、REST API - Flask

from flask import Flask, jsonifyapp = Flask(__name)@app.route('/api', methods=['GET'])
def get_data():data = {'message': 'Hello, API!'}return jsonify(data)if __name__ == '__main__':app.run()

官方文档: https://flask.palletsprojects.com/en/2.1.x/

还整理了30个更难一点的脚本实例,后续会发布出来。敬请期待

这篇关于20个硬核Python脚本的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/974023

相关文章

FCM聚类算法详解(Python实现iris数据集)

参考:https://blog.csdn.net/on2way/article/details/47087201 模糊C均值(Fuzzy C-means)算法简称FCM算法,是一种基于目标函数的模糊聚类算法,主要用于数据的聚类分析。理论成熟,应用广泛,是一种优秀的聚类算法。本文关于FCM算法的一些原理推导部分介绍,加上自己的理解和在课题项目中的应用以文字的形式呈现出来。 首先介绍一下模糊这个概

笔试当中的python输入操作

一般第一行是一个整数,就是代表后续输入多少行,我们可以用 str = int(input()) 来读取这个数字,如果是整数,就在前面加上一个int() 如果是多行的输入,我们可以使用 a = list(map(int, input().strip().split())) 把输入进来的按空格分开的数组给合起来,用逗号隔开,方法哦列表当中,如果也是整数,要记得用int 如果第一行的整数

Linux脚本重定向

Shell中可能经常能看到:>/dev/null  2>&1  eg:sudo kill -9 `ps -elf |grep -v grep|grep $1|awk '{print $4}'` 1>/dev/null 2>/dev/null 命令的结果可以通过%>的形式来定义输出 /dev/null 代表空设备文件 > 代表重定向到哪里,例如:echo "123" > /home/1

Zen of Python -Python之禅

在浏览Python官方文档时无意发现了这个彩蛋,只需在终端中import this The Zen of Python, by Tim PetersBeautiful is better than ugly.Explicit is better than implicit.Simple is better than complex.Complex is better than compli

Python内置函数oct()详解

Python中的oct()函数是一个内置函数,用于将一个整数转换成它的八进制字符串表示。 函数定义 oct()函数的基本语法如下: oct(x) x:一个整数。 函数返回x的八进制表示,以字符串形式。 基本用法 将整数转换为八进制 number = 64print(oct(number)) # 输出: '0o100' 转换负整数 number = -64print(o

Python筑基之旅-溯源及发展

目录 一、Python的起源 二、Python的版本更替及变化 三、Python的优缺点 四、Python的发展方向 五、Python之禅 六、推荐专栏/主页: 1、Python函数之旅:Functions 2、Python算法之旅:Algorithms 3、个人主页:https://myelsa1024.blog.csdn.net/ ​​​​​​​ 一、Python

Python专题:十六、异常处理(2)

异常的预判和防护 import randomnum = random.randint(1, 100) # 获得一个随机数is_done = False # 是否猜中的标记count = 0 # 玩家猜了几次while not is_done:guess = int(input('请输入一个[1, 100]的整数:'))if guess == num:is_done = Trueelif

理解 Python 中的 `super()` 与 `__init__()` 方法

在 Python 的面向对象编程中,super() 函数和 __init__() 方法是两个非常重要的概念。它们在类的继承和初始化过程中扮演着关键的角色。本文将深入探讨这两个概念的工作原理,并通过示例代码来展示它们的使用。 基本原理 __init__() 方法 __init__() 是一个特殊的方法,也称为类的构造器。当你创建一个类的新实例时,Python 会自动调用这个方法。它通常用于初始

python 合并 pdf

from pypdf import PdfMergerpdfs = ['file1.pdf', 'file2.pdf', 'file3.pdf', 'file4.pdf']merger = PdfMerger()for pdf in pdfs:merger.append(pdf)merger.write("result.pdf")merger.close() 参考 https://stack

Python——IO编程

IO在计算机中指Input/Output,也就是输入和输出。由于程序和运行时数据是在内存中驻留,由CPU这个超快的计算核心来执行,涉及到数据交换的地方,通常是磁盘、网络等,就需要IO接口。 比如你打开浏览器,访问新浪首页,浏览器这个程序就需要通过网络IO获取新浪的网页。浏览器首先会发送数据给新浪服务器,告诉它我想要首页的HTML,这个动作是往外发数据,叫Output,随后新浪服务器把网页发过来,