现在有一大堆英文参考文献,要将其中的图书和杂志分开,在deepseek中输入提示词:
你是一个Python编程专家,要完成一个Python脚本,完成任务如下:
读取文件:"D:\参考文献.xlsx"工作簿中的工作表“sheet1”
检测第一列所有单元格内容中是否含有字符串“vol.”或者“Vol.”,比如:
“A. D. Godley, trans., “The Histories of Herodotus”, vol. II, Cambridge, MA: Harvard University Press, 1921”
“F. A. Hayek, “The Legal and Political Philosophy of David Hume”, Il Politico, vol. 28, no. 4, (1963)”
“James Kurth, “The Real Clash,” The National Interest, Vol. 37 (Fall 1994)”
“F. A. Hayek, “The Legal and Political Philosophy of David Hume”, Il Politico, vol. 28, no. 4, (1963)”
以上4个单元格内容都是有字符串“vol.”的;
如果单元格中包含字符串“vol.”或者“Vol.”,那么把这个单元格内容移动到工作表“Sheet2”;
删除掉sheet1中包含字符串“vol.”或者“Vol.”的单元格内容;
注意:每一步都要输出信息到屏幕上
pandas库在较新的版本中已经弃用了append方法,建议使用concat方法来替代。此外,为了避免FutureWarning,我们可以使用iloc来访问DataFrame的行。
在写入Excel文件时,pandas默认不允许覆盖现有的工作表。我们可以通过设置if_sheet_exists参数来解决这个问题。
Deepseek生成的源代码:
import pandas as pd
from openpyxl import load_workbook
# 读取Excel文件
file_path = r"D:\参考文献.xlsx"
sheet_name = "Sheet1"
print(f"正在读取文件: {file_path}, 工作表: {sheet_name}")
# 读取工作表Sheet1
df = pd.read_excel(file_path, sheet_name=sheet_name)
# 检测第一列所有单元格内容中是否含有字符串“vol.”或者“Vol.”
target_strings = ["vol.", "Vol."]
# 创建一个空的DataFrame用于存储符合条件的行
filtered_df = pd.DataFrame(columns=df.columns)
print("正在检测第一列中的字符串...")
# 遍历第一列
indices_to_remove = []
for index, row in df.iterrows():
cell_content = str(row.iloc[0]) # 获取第一列的单元格内容
if any(target in cell_content for target in target_strings):
print(f"发现匹配的单元格内容: {cell_content}")
filtered_df = pd.concat([filtered_df, row.to_frame().T], ignore_index=True)
indices_to_remove.append(index)
# 如果没有找到匹配的行,输出提示信息
if filtered_df.empty:
print("未找到包含'vol.'或'Vol.'的单元格内容。")
else: