2016-03-24 27 views
0

我想诉诸一堆数字与Applescript。我对这门语言很陌生,我想我会请你帮忙。Applescript度假村堆数字

我有一组数字,看起来像这样在我的文本编辑文件:

v 0.186472 0.578063 1.566364 
v -0.186472 0.578063 1.566364 
v 0.335649 0.578063 1.771483 

我需要的是,求助于这些数字的脚本,使它看起来像这样:

(0.186472, 0.578063, 1.566364), 
(-0.186472, 0.578063, 1.566364), 
(0.335649, 0.578063, 1.771483), 

所以在每个数字之后,必须有一个逗号,并且总是必须将一行中的三个数字放在括号()中。最后,在每一行必须被删除之前,每个括号中的三个组和v之后必须有另一个逗号。

我只到目前为止设法摆脱每一个“V”使用:

set stringToFind to "v" 
set stringToReplace to "" 

但我现在卡住了,我希望寻求帮助。

+0

您好!如果你可以用缩进或反引号包围你的代码示例,这将有所帮助,因此它们以固定宽度的字体显示,并且更易于编辑和复制/粘贴。欢迎来到堆栈溢出! – Martin

+0

后续问题应该在新问题中提出。请在那里询问并在此处删除更新,您将得到帮助。之后我会删除此评论。 –

回答

0

要在AppleScript中查找和替换字符串,原生方法是使用text item delimiters。在每行上有用空格(或制表符)分隔的固定数量的值,使用text item delimiters,text items和字符串连接我们可以解决您的问题。

我在字符串的前面和后面添加了换行,以显示不包含4个单词的行被忽略。

set theString to " 
v 0.186472 0.578063 1.566364 
v -0.186472 0.578063 1.566364 
v 0.335649 0.578063 1.771483 
" 
set theLines to paragraphs of theString 

set oldTIDs to AppleScript's text item delimiters 


repeat with i from 1 to count theLines 
    set AppleScript's text item delimiters to {space, tab} 
    if (count of text items of item i of theLines) = 4 then 
     set theNumbers to text items 2 thru -1 of item i of theLines 
     set AppleScript's text item delimiters to ", " 
     set item i of theLines to "(" & (theNumbers as string) & ")," 
    else 
     set item i of theLines to missing value 
    end if 
end repeat 

set theLines to text of theLines 
set AppleScript's text item delimiters to linefeed 
set newString to theLines as string 
set AppleScript's text item delimiters to oldTIDs 
return newString 
+0

非常感谢!奇迹般有效!不过我想我遇到了一个小问题。该代码似乎将所有负值返回为正值。我相信这是一个简单的解决方法,但我的技能仅限于检测和解决问题。任何帮助? –

+0

我已经更新了帖子Järv,它现在使用'text items'而不是'words'并保留负值的前导连字符。 –