我正在尝试使用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
答案 0 :(得分:1)
最简单的方法是使用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,但没有为执行shell脚本调用设置区域设置。)
答案 1 :(得分:0)
您可以使用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”命令,并为用户:“显示对话框”或“选择从列表“或”选择文件“消息。