在Applescript中,我有一串单位数字:
0123456789
我想通过该字符串并在每个数字之间添加一个逗号,因此它会显示:
0,1,2,3,4,5,6,7,8,9
如何使用Applescript执行此操作?
注释
答案 0 :(得分:2)
您可以使用名为AppleScript's text item delimiters
的便捷功能,该功能允许您将文本分解(或“解析”为计算机行话),然后从这些段中提取数据。它们是一段文本中文本项的分隔符。一个简单的例子:
set prevTIDs to AppleScript's text item delimiters
set theString to "Don't-eat-the-yellow-snow"
set AppleScript's text item delimiters to "-" --tell AppleScript to break up strings at each occurrence of a hyphen '-' in a given string
set these_items to every text item of theString
//--> {"Don't", "eat", "the", "yellow", "snow"}
set AppleScript's text item delimiters to prevTIDs
return these_items
使用文本项分隔符恢复原始分隔符时,始终认为这是一种很好的做法。一旦更改了分隔符,它们将全局影响运行环境,直到该进程关闭并重新启动。
文本项分隔符的另一个用途是替换给定字符串中的单词或字符:
set prevTIDs to AppleScript's text item delimiters
set theString to "Don't eat the yellow snow"
set AppleScript's text item delimiters to "yellow" --the word you want to replace
set temp to every text item of theString
//--> {"Don't eat the", "snow"}
set AppleScript's text item delimiters to "pink" --the replacement word
set theString to temp as string
set AppleScript's text item delimiters to prevTIDs
return theString
//--> "Don't eat the pink snow"
但是,请注意,这会替换单词“yellow”的每个出现。我说这个的原因是考虑以下字符串:
If someone added one plus one, what would be the result?
如果您想将单词“one”替换为单词“two”,则在创建新分隔符时必须确保在“two”之前加上空格,否则结果字符串将如下所示: / p>
If sometwo added two plus two, what would be the result?
你要做的是基本上用逗号代替空字符串。您需要做的就是按照以下简单步骤来执行此操作:
""
set the list to every text item of yourString
),
set yourString to list as string
)return
你的字符串结果代码:
set prevTIDs to AppleScript's text item delimtiers
set myString to "0123456789"
set AppleScript's text item delimiters to ""
set the_list to every text item of myString
set AppleScript's text item delimiters to ","
set myString to the_list as string
set AppleScript's text item delimiters to prevTIDs
return myString
快乐的编码! :)
答案 1 :(得分:1)
这样的东西?
set theNumber to "3452678190"
set AppleScript's text item delimiters to ","
set theItems to every character of theNumber as string
set AppleScript's text item delimiters to ""
return theItems