Applescript:在光标处拆分句子-删除所选内容中的标点符号,大写字母并插入句点



我是AppleScript的新手,但认为它可以自动处理我有时处理的一个小麻烦。

比方说我写:"我喜欢披萨,在上面放培根!"但我决定把它分成两句:"我喜欢披萨。把培根放进去!"

我希望能够选择字符串",p"使用键盘快捷键,让脚本删除任何标点符号,添加句点,并将第一个字母大写。

我想好了如何设置"系统首选项">"键盘"来运行自动售货机服务,运行AppleScript,但我无法在谷歌上搜索到足够的信息来从头开始创建脚本。

任何帮助或指导都将是伟大的!

可选:由于Automator也支持其他解释器,因此不需要严格使用AppleScript。

这里有一个替代解决方案,它使用Run Shell Script操作来bashawk组合,从而减少代码:

  • 创建一个Automator服务,该服务:
    • any application中接收selected text
    • 已选中复选框Output replaces selected text
    • 包含Run Shell Script操作,代码如下
  • 然后调用该服务,并选择整句("我喜欢披萨,在上面放培根!")
awk -F ', ' '{ 
    printf $1   # print the first "field"; lines without ", " only have 1 field
    for (i=2; i<=NF; ++i) { # all other fields, i.e., all ", "-separated clauses.
       # Join the remaining clauses with ". " with their 1st char. capitalized.
      printf ". " toupper(substr($i,1,1)) substr($i,2)
    }
    printf "n" # terminate the output with a newline
  }'

注意事项:令人难以置信的是,awk(从OS X 10.9.2开始)没有正确处理外来字符——通过未修改的作品传递这些字符,但toupper()tolower()无法将它们识别为字母。因此,此解决方案将不能正确地用于包含外来字符的输入。必须大写;例如:"I like pizza, ṕut bacon on it!"不会将转换为

如果您:

  • 创建一个Automator服务,该服务:
    • any application中接收selected text
    • 已选中复选框Output replaces selected text
    • 包含Run AppleScript操作,代码如下
  • 然后调用服务,并选择整句("我喜欢披萨,在上面放培根!")

它应该做你想做的事。

on run {input, parameters}
    # Initialize return variable.
    set res to ""
    # Split the selection into clauses by ", ".
    set {orgTIDs, AppleScript's text item delimiters} to {AppleScript's text item delimiters, {", "}} #'
    set clauses to text items of item 1 of input
    set AppleScript's text item delimiters to orgTIDs #'
    # Join the clauses with ". ", capitalizing the first letter of all clauses but the first.
    repeat with clause in clauses
        if res = "" then
            set res to clause
        else
            set res to res & ". " & my capitalizeFirstChar(clause)
        end if
    end repeat
    # Return the result
    return res
end run
# Returns the specified string with its first character capitalized.
on capitalizeFirstChar(s)
    set {orgTIDs, AppleScript's text item delimiters} to {AppleScript's text item delimiters, {""}} #'
    set res to my toUpper((text item 1 of s) as text) & text items 2 thru -1 of s as text
    set AppleScript's text item delimiters to orgTIDs #'
    return res
end capitalizeFirstChar
# Converts the specified string (as a whole) to uppercase.
on toUpper(s)
    tell AppleScript to return do shell script "export LANG='" & user locale of (system info) & ".UTF-8'; tr [:lower:] [:upper:] <<< " & quoted form of s
end toUpper

相关内容

最新更新