45个Python实用小技巧(2)
导读:45个Python实用小技巧,16、正则表达式 import repattern = r'\d+' # 匹配1个或多个数字result = re.findall(pattern, "There are 42 apples and 123 oranges.") 17、日期操作 from datetime import datetime, timedelt
45个Python实用小技巧
16、正则表达式
import re
pattern = r'\d+' # 匹配1个或多个数字
result = re.findall(pattern, "There are 42 apples and 123 oranges.")
17、日期操作
from datetime import datetime, timedelta
current_date = datetime.now()
future_date = current_date + timedelta(days=7)
18、列表操作
numbers = [1, 2, 3, 4, 5]
# 过滤
evens = list(filter(lambda x: x % 2 == 0, numbers))
# 映射
squared = list(map(lambda x: x**2, numbers))
# 减少
from functools import reduce
product = reduce(lambda x, y: x * y, numbers)
19、字典操作
my_dict = {'a': 1, 'b': 2, 'c': 3}
# 获取值
value = my_dict.get('d', 0)
# 字典推导式
squared_dict = {key: value**2 for key, value in my_dict.items()}
20、线程并发
import threading
def print_numbers():
for i in range(5):
print(i)
thread = threading.Thread(target=print_numbers)
thread.start()
21、使用Asyncio实现并发
import asyncio
async def print_numbers():
for i in range(5):
print(i)
await asyncio.sleep(1)
asyncio.run(print_numbers())
22、使用Beautiful Soup实现网页爬虫
from bs4 import BeautifulSoup
import requests
url = "https://example.com"
response = requests.get(url)
soup = BeautifulSoup(response.text, 'html.parser')
title = soup.title.text
23、使用Flask实现RESTful API
from flask import Flask, jsonify, request
app = Flask(__name__)
@app.route('/api/data', methods=['GET'])
def get_data():
data = {'key': 'value'}
return jsonify(data)
if __name__ == '__main__':
app.run(debug=True)
24、使用unittest进行单元测试
import unittest
def add(x, y):
return x + y
class TestAddition(unittest.TestCase):
def test_add_positive_numbers(self):
self.assertEqual(add(2, 3), 5)
if __name__ == '__main__':
unittest.main()
25、与SQLite的数据库交互
import sqlite3
conn = sqlite3.connect('example.db')
cursor = conn.cursor()
# 只需SQL查询
cursor.execute('CREATE TABLE IF NOT EXISTS users (id INTEGER PRIMARY KEY, name TEXT)')
# 提交
conn.commit()
# 关闭链接
conn.close()
26、文件写入和读取
# 保存文件
with open('example.txt', 'w') as file:
file.write('Hello, Python!')
# 读取文件
with open('example.txt', 'r') as file:
content = file.read()
27、异常操作
try:
result = 10 / 0
except ZeroDivisionError as e:
print(f"Error: {e}")
except Exception as e:
print(f"Unexpected Error: {e}")
else:
print("No errors occurred.")
finally:
print("This block always executes.")
相关阅读
-
深入理解计算机科学:与、或、非逻辑运算符详解
正文核心介绍:深入理解计算机科学方面的讲解,相关内容具体如下: 逻辑运算符的基本概念 在计算机科学中,与、或、非是三种基本的逻辑运算符。 它们主要在布尔代数和逻辑电路设计中
-
域名备案流程及步骤 个人域名备案流程详细
一篇很详细的教程是关于域名备案流程及步骤和个人域名备案流程详细方面的讲解,一起来了解了解吧。 上一篇文章中我们讲了怎么注册域名,现在我们来讲解域名怎么备案。在中国,域名的
-
电脑服务器地址在哪里看 详解服务器端口设置方法
对于许多网友来说电脑服务器地址在哪里看和详解服务器端口设置方法方面的知识,接下来分享详细内容。 所谓高防服务器,只有防御大于100G的才能称之为高防服务器。那么高防服务器地址怎
-
小程序服务器配置多大够用? 小程序服务器需求量如何确定?
为大家分享小程序服务器配置多大够用的相关经验,请看下面详细的介绍。 了解小程序服务器的大小和要求对于确保小程序的高效运行非常重要。 下面不念将介绍小程序服务器的大小和要求,


