您的脚本不起作用,因为您正在构建一个单词列表。空格(包括不间断空格)是单词分隔符,因此它们不在您的单词列表 (MW) 中。
如果我们使用不间断空格作为文本项分隔符,它将起作用:
use scripting additions
set theResult to {}
set ourText to "Hello my friends Jon Doe, Jane Doe and Joe Doe!" # Each name contains a no-break space
set findThis to character id 160 # Decimal notation of U+00A0 (no-break space)
set saveTID to AppleScript's text item delimiters
set AppleScript's text item delimiters to findThis # The no-break space
set countTextItems to count of text items of ourText
if countTextItems > 1 then
repeat with i from 1 to countTextItems - 1
set end of theResult to word -1 of text item i of ourText & findThis & word 1 of text item (i + 1) of ourText
end repeat
else
set theResult to "[no character id " & id of findThis & " found]"
end if
set AppleScript's text item delimiters to linefeed
display dialog theResult as text
set AppleScript's text item delimiters to saveTID
输入(ourText
):
你好,我的朋友 Jon[noBreakSpace]Doe、Jane[noBreakSpace]Doe 和 Joe[noBreakSpace]Doe!
输出:
请注意,这将在以下情况下失败
我的朋友 J.[noBreakSpace]Doe
因为我们word
在重复循环中使用。
如果您经常遇到此类情况,请用and替换word -1
and 。然后输出将仅包含空格周围的两个字符,但对于搜索目的,这仍然足够。word 1
text -1
text 1