
现在有一大堆英文参考文献,要将其中的图书和杂志分开,在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:
print("已找到匹配的单元格内容,正在移动到Sheet2并从Sheet1中删除...")
# 删除Sheet1中匹配的行
df = df.drop(indices_to_remove)
# 将匹配的行写入Sheet2
with pd.ExcelWriter(file_path, mode='a', engine='openpyxl', if_sheet_exists='replace') as writer:
# 写入Sheet1
df.to_excel(writer, sheet_name="Sheet1", index=False)
# 写入Sheet2
filtered_df.to_excel(writer, sheet_name="Sheet2", index=False)
print("已成功将匹配的单元格内容移动到Sheet2并从Sheet1中删除。")

程序运行成功。
本文分享自 Dance with GenAI 微信公众号,前往查看
如有侵权,请联系 cloudcommunity@tencent.com 删除。
本文参与 腾讯云自媒体同步曝光计划 ,欢迎热爱写作的你一起参与!