十个常见的 Python 脚本 (详细介绍 + 代码举例)
以下是十个常见的Python脚本,每个脚本都有详细的描述和代码示例:
- 计算器脚本:
# 计算器脚本
def calculator(expression):
return eval(expression)
# 使用示例
result = calculator("1 + 2 * 3")
print(result) # 输出: 7
- 简单的交互式提示符脚本:
# 简单的交互式提示符脚本
import cmd
class SimplePrompt(cmd.Cmd):
def do_greet(self, name):
"Greet user"
print(f"Hello, {name}!")
# 使用示例
SimplePrompt().cmdloop()
- 文件分割器脚本:
# 文件分割器脚本
def split_file(file_path, chunk_size=1024):
with open(file_path, 'rb') as file:
chunk = file.read(chunk_size)
while chunk:
yield chunk
chunk = file.read(chunk_size)
# 使用示例
for chunk in split_file('example.txt', 100):
print(chunk)
- 简单的网页抓取脚本:
# 简单的网页抓取脚本
import requests
def fetch_website(url):
response = requests.get(url)
if response.status_code == 200:
return response.text
else:
return "Error fetching website"
# 使用示例
content = fetch_website('https://www.example.com')
print(content)
- 简单的排序算法(冒泡排序):
# 冒泡排序算法
def bubble_sort(arr):
n = len(arr)
for i in range(n):
for j in range(0, n - i- 1):
if arr[j] > arr[j+1]:
arr[j], arr[j+1]= arr[j+1], arr[j]
return arr
# 使用示例
arr = [64, 34, 25, 12, 22, 11, 90]
sorted_arr = bubble_sort(arr)
print("Sorted array is:", sorted_arr)
- 简单的文件下载器脚本:
# 简单的文件下载器脚本
import requests
def download_file(url, file_path):
response = requests.get(url)
with open(file_path, 'wb') as file:
file.write(response.content)
# 使用示例
download_file('https://www.example.com/image.jpg', 'image.jpg')
- 简单的文件查看器脚本:
# 简单的文件查看器脚本
import os
def view_file(file_path):
with open(file_path, 'r') as file:
print(file.read())
# 使用示例
view_file('example.txt')
- 简单的文件加密器脚本:
# 简单的文件加密器脚本
import os
def encrypt_file(file_path, key):
with open(file_path, 'rb') as file:
data = file.read()
encrypted_data = bytes([(ord(x) ^ key) for x in data])
return encrypted_data
# 使用示例
encrypted_data = encrypt_file('example.txt', 123)
with open('example_encrypt
评论已关闭