Python实例题:使用Pvthon3编写系列实用脚本
目录
Python实例题
题目
1. 文件重命名脚本
csv_data_statistics.py
file_rename.py
web_crawler.py
2. CSV 文件数据统计脚本
3. 简单的网页爬虫脚本
运行思路
文件重命名脚本
CSV 文件数据统计脚本
简单的网页爬虫脚本
注意事项
Python实例题
题目
使用Pvthon3编写系列实用脚本
1. 文件重命名脚本
此脚本能够批量重命名指定目录下的文件,给文件名添加前缀。
csv_data_statistics.py
import csvdef calculate_column_sum(csv_file, column_index):"""计算 CSV 文件中指定列的总和:param csv_file: CSV 文件路径:param column_index: 列索引(从 0 开始):return: 列数据的总和"""total = 0try:with open(csv_file, 'r', encoding='utf-8') as file:reader = csv.reader(file)next(reader) # 跳过标题行for row in reader:try:value = float(row[column_index])total += valueexcept (IndexError, ValueError):continueexcept FileNotFoundError:print(f"指定的 CSV 文件 {csv_file} 未找到。")return totalif __name__ == "__main__":csv_file = input("请输入 CSV 文件的路径: ")column_index = int(input("请输入要统计的列索引(从 0 开始): "))result = calculate_column_sum(csv_file, column_index)print(f"指定列的总和为: {result}")
file_rename.py
import osdef rename_files(directory, prefix):"""批量重命名指定目录下的文件:param directory: 目录路径:param prefix: 要添加的前缀"""try:for filename in os.listdir(directory):if os.path.isfile(os.path.join(directory, filename)):new_filename = prefix + filenameos.rename(os.path.join(directory, filename), os.path.join(directory, new_filename))print(f"已将 {filename} 重命名为 {new_filename}")except FileNotFoundError:print(f"指定的目录 {directory} 未找到。")except PermissionError:print(f"没有权限对目录 {directory} 进行操作。")if __name__ == "__main__":directory = input("请输入要重命名文件所在的目录路径: ")prefix = input("请输入要添加的前缀: ")rename_files(directory, prefix)
web_crawler.py
import requests
from bs4 import BeautifulSoupdef extract_links(url):"""从指定网页中提取所有链接:param url: 网页的 URL:return: 链接列表"""try:response = requests.get(url)response.raise_for_status()soup = BeautifulSoup(response.text, 'html.parser')links = []for link in soup.find_all('a'):href = link.get('href')if href:links.append(href)return linksexcept requests.RequestException as e:print(f"请求网页时出现错误: {e}")return []if __name__ == "__main__":url = input("请输入要提取链接的网页 URL: ")links = extract_links(url)for link in links:print(link)
2. CSV 文件数据统计脚本
该脚本用于读取 CSV 文件,并统计某一列数据的总和。
3. 简单的网页爬虫脚本
此脚本可以从网页中提取所有的链接。
运行思路
文件重命名脚本
- 把代码保存为
file_rename.py
文件。 - 在终端运行
python file_rename.py
。 - 按照提示输入要重命名文件所在的目录路径和要添加的前缀。
CSV 文件数据统计脚本
- 保存代码为
csv_data_statistics.py
文件。 - 在终端运行
python csv_data_statistics.py
。 - 输入 CSV 文件的路径和要统计的列索引。
简单的网页爬虫脚本
- 确保已经安装了
requests
和beautifulsoup4
库:pip install requests beautifulsoup4
。 - 保存代码为
web_crawler.py
文件。 - 在终端运行
python web_crawler.py
。 - 输入要提取链接的网页 URL。
注意事项
- 文件路径:输入的文件路径和目录路径要确保正确,否则会出现文件未找到的错误。
- 网络请求:网页爬虫脚本在运行时要注意目标网站的反爬机制,避免频繁请求导致 IP 被封禁。
- 数据格式:CSV 文件数据统计脚本假设指定列的数据为可转换为浮点数的格式,若格式不符可能会影响统计结果。