我正在尝试使用Applescript将千位分隔符(逗号)放入我的数字中。我在网上找到了两个子程序,据说可以做到这一点,但似乎没有什么是正确的。
它给了我各种各样的随机格式。我试着从整数,到实数,到小整数,到字符串,等等。似乎什么都没用。
我传递的内容:
set perCapita2014 to avgHHinc2014 / avgPopHH2014 as integer -- results 17005
调用:
set finalPerCapita2014 to (comma_delimit(perCapita2014)) -- results 0.,0.5
子程序:(显然它需要这两个)
on number_to_string(this_number)
set this_number to this_number as string
if this_number contains "E+" then
set x to the offset of "." in this_number
set y to the offset of "+" in this_number
set z to the offset of "E" in this_number
set the decimal_adjust to characters (y - (length of this_number)) thru ¬
-1 of this_number as string as number
if x is not 0 then
set the first_part to characters 1 thru (x - 1) of this_number as string
else
set the first_part to ""
end if
set the second_part to characters (x + 1) thru (z - 1) of this_number as string
set the converted_number to the first_part
repeat with i from 1 to the decimal_adjust
try
set the converted_number to ¬
the converted_number & character i of the second_part
on error
set the converted_number to the converted_number & "0"
end try
end repeat
return the converted_number
else
return this_number
end if
end number_to_string
on comma_delimit(this_number)
set this_number to this_number as string
if this_number contains "E" then set this_number to number_to_text(this_number)
set the num_length to the length of this_number
set the this_number to (the reverse of every character of this_number) as string
set the new_num to ""
repeat with i from 1 to the num_length
if i is the num_length or (i mod 3) is not 0 then
set the new_num to (character i of this_number & the new_num) as string
else
set the new_num to ("," & character i of this_number & the new_num) as string
end if
end repeat
return the new_num
end comma_delimit
最简单的方法是使用do shell脚本使用复杂的perl调用:
set perCapita2014 to (avgHHinc2014 / avgPopHH2014) as integer
set finalPerCapita2014 to do shell script "echo " & perCapita2014 & " | perl -lpe'1 while s/^([-+]?\d+)(\d{3})/$1,$2/'"
Applescript不擅长这样的文本处理。(我第一次尝试使用printF,但语言环境没有为do shell脚本调用设置)
你可以用一种更简单的方式在PHP中做到这一点,因为PHP有一个为数字添加逗号的内置函数。
on comma_delimit(theNumber)
set thePHPScript to "echo number_format(" & theNumber & ");"
set theShellScript to "php -r" & space & quote & thePHPScript & quote
set theNumberTextWithCommas to do shell script theShellScript
return theNumberTextWithCommas
end comma_delimit
一般来说,你不应该在AppleScript本身做任何实际的处理,因为它不是为此而设计的。它是为应用程序和用户之间的消息传递而设计的——用于向应用程序或用户发送输入并获取输出并将其用作下一个应用程序或用户的输入。基本上与bash管道相同,但在GUI中。
所以AppleScript不擅长处理文本的原因是因为AppleScript擅长向BBEdit或Perl这样的应用程序发送消息,让它们处理文本。而且AppleScript并不擅长处理图像,因为AppleScript擅长向Photoshop或Image Events等应用发送信息,让它们处理图像。一个理想的AppleScript只是一堆消息在应用程序和用户之间来回传递,通过"告诉应用程序"块,"执行shell脚本"命令,"执行javascript"命令,以及对用户:"显示对话框"或"从列表中选择"或"选择文件"消息。