如何修改AppleScript代码,实现标题大写时忽略指定常用词列表?
如何修改AppleScript代码,实现标题大写时忽略指定常用词列表?
嗨,这个问题我刚好有思路!你已经整理好了不该大写的单词列表,现在只需要调整一下标题处理的逻辑——既要保留Python脚本不破坏特殊字符的优势,又要让中间位置的指定单词保持小写,同时保证标题首尾的单词必须大写(符合英文标题的常规规范)。
核心思路
原来的Python title() 方法会无脑把每个单词首字母大写,现在我们要做的是:
- 把你定义的
DoNotCapList传递给Python脚本,转成快速查找的集合 - 用正则匹配标题里的每个单词,避免破坏连字符、逗号等特殊字符
- 对每个单词做判断:
- 如果是标题的第一个单词,不管在不在列表里都首字母大写
- 如果是中间的单词,要是在
DoNotCapList里就保持小写,否则首字母大写
修改后的完整代码
set DoNotCapList to {"a", "and", "as", "at", "but", "by", "down", "for", "from", "if", "in", "into", "like", "near", "nor", "of", "off", "on", "once", "onto", "or", "over", "past", "so", "than", "that", "to", "upon", "when", "with", "yet"} tell application "GarageSale 9.8.1" repeat with theListing in (get selected ebay listings) set des to get the title of theListing set the title of theListing to my titlecase(des, DoNotCapList) end repeat end tell on titlecase(txt, doNotCap) -- 将AppleScript列表转换为Python可识别的集合格式 set pythonDoNotCap to "{' " & (join of doNotCap using "', '") & "'}" -- 构造Python处理脚本,实现智能大小写逻辑 set pythonScript to "import sys, re do_not_cap = " & pythonDoNotCap & " txt = sys.argv[1].decode('utf8') def process_word(match): word = match.group() -- 标题第一个单词强制大写 if match.start() == 0: return word.capitalize() lower_word = word.lower() -- 不在忽略列表的单词首字母大写,在列表的保持小写 return lower_word if lower_word in do_not_cap else word.capitalize() -- 匹配所有单词(兼容带连字符、撇号的单词,不破坏原格式) formatted_title = re.sub(r'[\\w\\'-]+', process_word, txt) print(formatted_title.encode('utf8'))" -- 执行Python脚本并返回结果 return do shell script "python -c " & quoted form of pythonScript & " " & quoted form of txt end titlecase
关键细节说明
- 修正了原列表的小问题:我把你原列表里的
"off "(带空格)改成了"off",避免匹配时因为多余空格导致判断错误 - 正则匹配更友好:用
[\w\'-]+匹配单词,能兼容标题里的连字符(比如"state-of-the-art")、撇号(比如"seller's"),不会把这些特殊字符和单词拆分,完美保留你原标题的格式 - 符合英文标题规范:强制标题第一个单词大写,即使它在忽略列表里(比如标题开头的"A"还是会保留大写,符合常规排版)
- 易于维护:之后你要修改忽略列表的话,直接改AppleScript开头的
DoNotCapList就行,不用动处理逻辑部分
备注:内容来源于stack exchange,提问作者user5671178
相关产品推荐
相关产品推荐

