文件夹文件
遍历指定文件夹中的PDF文件,从文件名中提取书名信息,然后生成符合NoteExpress导入格式的文本文件。
代码如下:
import os import re # ============================================ # 配置区域 - 请根据你的实际情况修改 # ============================================ # PDF文件所在的文件夹路径 folder_path = r"D:\BaiduNetdiskDownload\战史丛书102卷" # 输出文件路径 output_path = r"D:\BaiduNetdiskDownload\BookEndnote.txt" # ============================================ # 主程序 # ============================================ def extract_info(filename): """ 从PDF文件名中提取卷数信息和书名 文件名格式示例:戦史叢書第073巻 関東軍<2>関特演・終戦時の対ソ戦.pdf 返回: (卷数信息, 书名) """ # 去掉.pdf后缀 name_without_ext = os.path.splitext(filename)[0] # 提取卷数:匹配 "戦史叢書第XXX巻" volume_match = re.search(r'(戦史叢書第\d+巻)', name_without_ext) volume = volume_match.group(1) if volume_match else "" # 提取书名:去掉卷数部分和前面的空格/全角空格 book_title = re.sub(r'戦史叢書第\d+巻\s*[ \s]*', '', name_without_ext).strip() return volume, book_title def main(): # 检查文件夹是否存在 if not os.path.exists(folder_path): print(f"错误:文件夹不存在 - {folder_path}") print("请检查路径是否正确!") return # 存储所有记录 records = [] # 获取所有PDF文件并排序 pdf_files = [f for f in os.listdir(folder_path) if f.lower().endswith('.pdf')] pdf_files.sort() # 按文件名排序(保持卷数顺序) print(f"找到 {len(pdf_files)} 个PDF文件") print("=" * 60) # 遍历所有PDF文件 for idx, filename in enumerate(pdf_files, 1): volume, book_title = extract_info(filename) # 生成NoteExpress兼容格式的记录 # NoteExpress支持的字段标签: # %0 文献类型 (Book/书籍) # %A 作者 # %T 标题(完整书名含卷数) # %B 副标题/丛书名 # %I 出版社 # %D 年份 # %V 卷号 # %N 期号 # %P 页数 # %X 摘要 # %@ ISBN # %U URL # %K 关键词 # 标题格式:戦史叢書第073巻 関東軍<2>関特演・終戦時の対ソ戦 full_title = f"{volume} {book_title}" if volume else book_title record = f"""%0 Book %A 防衛庁防衛研修所戦史室 %T {book_title} %B 戦史叢書 %V {volume.replace('戦史叢書', '')} %I 朝雲新聞社 %C 東京 %D 1980 %K 日本战史,防卫厅,战史丛书,太平洋战争 """ records.append(record) # 显示进度 if idx <= 5 or idx == len(pdf_files): print(f"[{idx:03d}/{len(pdf_files)}] {full_title}") elif idx == 6: print("...") # 将所有记录写入文件(NoteExpress推荐使用UTF-8编码) with open(output_path, 'w', encoding='utf-8') as f: f.write('\n'.join(records)) print("=" * 60) print(f"✅ 成功生成 {len(records)} 条记录") print(f"📄 文件已保存至: {output_path}") print("\n💡 导入NoteExpress步骤:") print(" 1. 打开 NoteExpress") print(" 2. 点击【文件】→【导入题录】") print(" 3. 选择生成的 BookEndnote.txt 文件") print(" 4. 过滤器选择 'NoteExpress' 格式") print(" 5. 指定目标文件夹,点击【开始导入】") print("\n📋 生成的字段说明:") print(" %T 标题:包含完整卷数和书名(如:戦史叢書第073巻 関東軍<2>...)") print(" %B 丛书名:戦史叢書") print(" %V 卷号:纯数字(如:073)") print(" %A 作者:防衛庁防衛研修所戦史室") print(" %I 出版社:朝雲新聞社") print(" %D 年份:1966-1980(丛书出版年代)") if __name__ == "__main__": main()网站表格
如下代码,完成书目的生成。
# -*- coding: utf-8 -*- import re import requests from bs4 import BeautifulSoup # 目标网站 URL = "http://www.tbcas.jp/ja/lib/lib1/" # 清理文本空白 def clean_text(s): return re.sub(r'\s+', ' ', s.strip()) # 解析网页表格 def parse_page(html): soup = BeautifulSoup(html, 'html.parser') table = soup.find('table', border="1") rows = table.find_all('tr')[1:] # 跳过表头 records = [] for row in rows: cols = row.find_all(['th', 'td']) if len(cols) < 7: continue # 提取每一列 req_id = clean_text(cols[0].get_text()) title_author= clean_text(cols[1].get_text()) vol = clean_text(cols[2].get_text()) pub_info = clean_text(cols[3].get_text()) phys_desc = clean_text(cols[4].get_text()) series = clean_text(cols[5].get_text()) link_tag = cols[6].find('a') url = link_tag['href'].strip() if link_tag else '' # 拆分书名 / 作者 author = "" if '/' in title_author: title_part, author_part = title_author.split('/', 1) title = title_part.strip() author = re.sub(r'[\[]\].]', '', author_part).strip() else: title = title_author.strip() # 完整书名(含卷次) full_title = f"{title} {vol}".strip() # ============================================== # 【核心修改】拆分:出版地 + 出版社 + 年份 # 格式例:上海 : 中支経済研究所,1939. # ============================================== pub_place = "" publisher = "" year = "" # 匹配 出版地:出版社,年份 match = re.search(r'^(.*?)\s*:\s*(.*?)\s*,\s*(\d{4})', pub_info) if match: pub_place = match.group(1).strip() # 出版地点 publisher = match.group(2).strip() # 出版社 year = match.group(3).strip() # 年份 else: # 匹配 出版地:出版社 match2 = re.search(r'^(.*?)\s*:\s*(.*?)[,.]', pub_info) if match2: pub_place = match2.group(1).strip() publisher = match2.group(2).strip() # 提取页数 pages = "" page_match = re.search(r'(\d.+?p)', phys_desc) if page_match: pages = page_match.group(1).strip() # ============================== # 生成 NoteExpress 标准格式 # ============================== ne = [] ne.append("%0 Book") # 文献类型 if author: ne.append(f"%A {author}") # 作者 ne.append(f"%T {full_title}") # 书名 if series: ne.append(f"%B {series}") # 丛书名 if pub_place: ne.append(f"%C {pub_place}")# 出版地点(新增) if publisher: ne.append(f"%I {publisher}")# 出版社 if year: ne.append(f"%D {year}") # 年份 if pages: ne.append(f"%P {pages}") # 页数 if url: ne.append(f"%U {url}") # 链接 ne.append("") # 每条记录空行分隔 records.append('\n'.join(ne)) return '\n'.join(records) # 主程序 def main(): headers = { "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36" } resp = requests.get(URL, headers=headers, timeout=20) resp.encoding = 'utf-8' resp.raise_for_status() ne_content = parse_page(resp.text) # 保存文件 with open("东洋文库书目_NoteExpress格式.txt", "w", encoding="utf-8") as f: f.write(ne_content) print("✅ 已生成可直接导入的 NoteExpress 文件!") print("\n【示例输出】") print(ne_content[:800]) if __name__ == "__main__": main()csv文件
又如,如下数据网站中,将题录下载完毕后,导出为csv文件。
https://www.jacar.archives.go.jp/das/meta/CA0207020200?sf=seq_a&rows=200&vt=b&page=2
采用如下代码:
# -*- coding: utf-8 -*- import pandas as pd import re def csv_to_noteexpress(): csv_file_path = "result_20260520211546.csv" # 你的CSV文件名 output_path = "NoteExpress_导入文件.txt" # 输出文件名 # 关键修复:sep=',' 自动识别逗号分隔 df = pd.read_csv(csv_file_path, sep=',', encoding='utf-8') df = df.fillna('') # 空值处理 with open(output_path, 'w', encoding='utf-8') as f: for _, row in df.iterrows(): # 读取字段(完全匹配你的列名) レファレンスコード = str(row["レファレンスコード"]).strip() 標題 = str(row["標題"]).strip() 階層 = str(row["階層"]).strip() 所蔵館請求番号 = str(row["所蔵館における請求番号"]).strip() 画像数 = str(row["画像数"]).strip() # ========== NoteExpress 格式输出 ========== f.write("%0 Book\n") # 文献类型 f.write("%A 防衛省防衛研究所\n") # 作者 f.write(f"%T {標題}\n") # 标题 f.write(f"%B {階層}\n") # 丛书名 f.write(f"%C 東京\n") # 出版社(自动提取) publisher = "防衛省防衛研究所" match = re.search(r"所蔵館:([^)]+)", 所蔵館請求番号) if match: publisher = match.group(1) f.write(f"%I {publisher}\n") # 年份(明治、大正、昭和 统一转公历) year = "不明" # 明治 1868年开始 meiji_match = re.search(r"明治(\d{1,2})年", 標題) if meiji_match: year = str(1867 + int(meiji_match.group(1))) # 大正 1912年开始 elif re.search(r"大正(\d{1,2})年", 標題): taisho_match = re.search(r"大正(\d{1,2})年", 標題) year = str(1911 + int(taisho_match.group(1))) # 昭和 1926年开始 elif re.search(r"昭和(\d{1,2})年", 標題): showa_match = re.search(r"昭和(\d{1,2})年", 標題) year = str(1925 + int(showa_match.group(1))) f.write(f"%D {year}\n") # 卷号 vol = "" vol_match = re.search(r"第(\d+)[巻号]", 標題) if vol_match: vol = vol_match.group(1) if vol: f.write(f"%V {vol}\n") f.write(f"%P {画像数}\n") # 页数 # 摘要 摘要 = f"参考代码: {レファレンスコード} | 馆藏号: {所蔵館請求番号} | 图片数: {画像数}" f.write(f"%X {摘要}\n") f.write("%@ \n") # ISBN f.write("%U \n") # URL # 关键词 keywords = 階層.replace(">", "; ") f.write(f"%K {keywords}\n") f.write("\n") # 文献分隔 print("✅ 转换完成!") print(f"📄 生成文件:{output_path}") print(f"📊 共处理:{len(df)} 条文献") # 直接运行 if __name__ == "__main__": csv_to_noteexpress()可以生成NoteExpress可以输入的形式。
即可完成。