AppleScript基于制表符分隔TXT生成iTunes播放列表的重复项校验实现
实现播放列表去重添加的改法
直接基于现有逻辑调整,不需要重构原有流程,核心是在复制操作前新增目标播放列表的存在性校验:
- 提前把目标播放列表的现有曲目全部加载到内存缓存,减少和iTunes的重复通信开销
- 每次处理TSV行时,先通过缓存校验是否已有同曲名、同艺术家的条目,只有无重复时才执行复制
- 补全原代码中写残的错误捕获逻辑,避免匹配不到曲目时脚本直接中断
- 修掉原代码重复多次读取TSV文件的冗余问题,减少文件IO拖慢处理速度
修正后的完整可运行代码
-- 单次读取TSV文件内容 set thisTSVFile to (choose file with prompt "Select the TSV file") set theList to readTabSeparatedValuesFile(thisTSVFile) tell application "iTunes" set myPlaylist to playlist "InSLtxtLists" set sourcePlaylist to playlist "Music" -- 缓存目标播放列表的所有现有曲目,供后续去重校验使用 set existingPlaylistTracks to every track of myPlaylist end tell -- 逐行处理TSV内容,从第二行开始跳过表头 repeat with i from 2 to count of items in theList set currentRowCells to item i of theList set trackName to item 1 of currentRowCells set trackArtist to item 2 of currentRowCells tell application "iTunes" try -- 去重校验:统计目标播放列表中匹配同曲名、同艺术家的条目数量 set duplicateCount to count of (existingPlaylistTracks whose name is trackName and artist is trackArtist) -- 只有不存在重复条目时才执行复制操作 if duplicateCount is 0 then set matchedSourceTrack to first track of sourcePlaylist whose name is trackName and artist is trackArtist duplicate matchedSourceTrack to myPlaylist -- 把新添加的曲目同步加入缓存,避免同次运行中TSV有重复行导致重复添加 set end of existingPlaylistTracks to matchedSourceTrack end if on error errMsg -- 匹配不到源曲库曲目时直接跳过,不中断整个流程 log "第" & i & "行处理跳过:未在源曲库匹配到 " & trackName & " - " & trackArtist & ",详细错误:" & errMsg end try end tell delay 0.05 end repeat -- 保留原有TSV读取逻辑,新增空行过滤 on readTabSeparatedValuesFile(thisTSVFile) try set dataBlob to every paragraph of (read thisTSVFile) set tableData to {} set AppleScript's text item delimiters to tab repeat with i from 1 to count of dataBlob set currentRowItems to every text item of (item i of dataBlob) -- 过滤空行,避免空行触发匹配异常 if (count of currentRowItems) ≥ 2 then set end of tableData to currentRowItems end repeat set AppleScript's text item delimiters to "" return tableData on error errorMessage number errorNumber set AppleScript's text item delimiters to "" error errorMessage number errorNumber end try end readTabSeparatedValuesFile
补充说明
- 匹配规则完全沿用原有的“曲名+艺术家”双字段匹配,不会改变原有逻辑的匹配精度
- 缓存机制会让整体处理速度比原代码快很多,原代码每轮循环都要和iTunes通信一次查目标列表,现在整个循环过程只需要第一次加载缓存,后续校验都在本地完成
- 就算TSV文件内部存在重复的同曲名同艺术家行,脚本运行过程中也不会因为缓存的更新逻辑重复添加
内容的提问来源于stack exchange,提问作者tardy pigeon
相关产品推荐
相关产品推荐

