如何在Applescript中为一串数字添加逗号?

时间:2012-01-27 22:13:21

标签: string macos parsing applescript

在Applescript中,我有一串单位数字:

0123456789

我想通过该字符串并在每个数字之间添加一个逗号,因此它会显示:

0,1,2,3,4,5,6,7,8,9

如何使用Applescript执行此操作?

注释

  • 我希望输入和输出都是“string”类型 - 不是列表。
  • 数字将始终为单位数字。

2 个答案:

答案 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?

你要做的是基本上用逗号代替空字符串。您需要做的就是按照以下简单步骤来执行此操作:

  1. 创建一个变量以存储
  2. 中的当前分隔符
  3. 创建一个变量以将字符串存储在
  4. 将分隔符更改为空字符串""
  5. 将您的字符串强制转换为列表(即set the list to every text item of yourString
  6. 将分隔符更改为逗号,
  7. 将新创建的列表强制转换为字符串(即set yourString to list as string
  8. 恢复旧分隔符
  9. return你的字符串
  10. 结果代码:

    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