QH7B 发表于 2026-1-11 18:42:22

求批量重命名字体的工具

如题,搜索到了这个python脚本:

https://raw.githubusercontent.com/easyhard007/Chinese-font-files-batch-rename/refs/heads/main/rename_font.py
但是这个脚本好像在处理ttc字体时会报错,所以不知道有没有大佬能改进一下它,输出由“&”连接的名称或者单独的 ttf 文件都可以。

ktuup6 发表于 2026-1-11 23:44:53

这样改你看行不行

import traceback

from fontTools.ttLib import TTFont, TTCollection
import re
import os
import argparse

# 默认目标文件夹
folder_path = './'

# 创建解析器
parser = argparse.ArgumentParser(description='命令行参数解析')

# 装有ttf或者otf字体的目标文件夹
parser.add_argument('-d', '--directory', type=str, help='目标文件夹')

# 解析参数
args = parser.parse_args()

if(args.directory!=None):
    folder_path = str(args.directory)
else:
    folder_path = './'
   

# 判断字符串中是否包含中文
def contains_chinese(text):
    return re.search(r'[\u4e00-\u9fff]', text) is not None

# 获取指定.ttf字体文件的内部中文名,如果没有中文名将使用英文名
def get_font_chinese_name(ttfFile):
    if ttfFile.lower().endswith(".ttc"):
      font_collection = TTCollection(ttfFile).fonts
    else:
      font_collection =
    names = []
    for font in font_collection:
      name_dict = {}#名称字典, 如果有多个中文名,按优先级序列选择(简体中文>繁体中文,windows>mac),如果没有中文名,则按优先级选择英文名(英语美国>英语英国,windows>mac)
      name_priority =
      for i, font_name in enumerate(font['name'].names):
            # print(i,font_name,font_name.langID,font_name.nameID)
            if font_name.nameID == 4: #包含字体家族详细信息:
                try:
                  name_dict = font_name.toUnicode()
                except Exception:
                  continue

      # 按优先级序列搜索
      for lang_id in name_priority:
            if lang_id in name_dict.keys():
                names.append(name_dict.replace(" ","-"))
                break
      else:
            break

    if not names:
      print("错误:",ttfFile,"无法找到中文名或英文名。")
      return -1
    else:
      return '&'.join(names)

#重命名文件
def rename_file(old_name, new_name):
    try:
      os.rename(old_name, new_name)
      print(f"文件 {old_name} 已成功重命名为 {new_name}")
    except FileNotFoundError:
      print(f"文件 {old_name} 不存在,请检查路径是否正确。")

#批量重命名文件
if __name__ == "__main__":
    for root, dirs, files in os.walk(folder_path):
      for filename in files:
            if filename.lower().endswith(".ttf") or filename.lower().endswith(".otf") or filename.lower().endswith(".ttc"):
                ttfFile = os.path.join(root, filename)
                _, fileExtension = os.path.splitext(filename)
                try:
                  c_name = get_font_chinese_name(ttfFile)
                  if c_name==-1: continue
                  newFileName = os.path.join(root,c_name+fileExtension)
                  rename_file(ttfFile,newFileName)
                except Exception as e:
                  traceback.print_exc()


QH7B 发表于 2026-1-12 13:33:05

ktuup6 发表于 2026-1-11 23:44
这样改你看行不行

可以了!非常感谢大佬帮忙修改!
页: [1]
查看完整版本: 求批量重命名字体的工具