首页 > 解决方案 > AppleScript:如何从字符串中提取数字?

问题描述

我正在编写一个脚本,以访问有关 Corona 的 NYT 网站,获取美国数据,提取数字(总数、死亡人数)并向我发送通知。我很接近,但是当我提取数字并显示它们时,它们被放在一起(即 700021 而不是 7000,21)。我的问题是:

如何提取数字以便描绘它们?

这是代码:

set theURL to "https://www.nytimes.com/interactive/2020/world/coronavirus-maps.html?action=click&pgtype=Article&state=default&module=styln-coronavirus&variant=show&region=TOP_BANNER&context=storyline_menu"

tell application "Safari" to make new document with properties {URL:theURL}

tell application "System Events"
    repeat until exists (UI elements of groups of toolbar 1 of window 1 of application process "Safari" whose name = "Reload this page")
        delay 0.5
    end repeat
end tell

to getInputByClass(theClass, num)
    tell application "Safari"
        set input to do JavaScript "
document.getElementsByClassName('" & theClass & "')[" & num & "].innerText;" in document 1
    end tell
    return input
end getInputByClass

set myVar to getInputByClass("g-body ", 5)

on returnNumbersInString(inputString)
    set s to quoted form of inputString
    do shell script "sed s/[a-zA-Z\\']//g <<< " & s
    set dx to the result
    set numlist to {}
    repeat with i from 1 to count of words in dx
        set this_item to word i of dx
        try
            set this_item to this_item as number
            set the end of numlist to this_item
        end try
    end repeat
    return numlist
end returnNumbersInString

set theNums to returnNumbersInString(myVar) as text

display notification "COVID-19 UPDATE" subtitle theNums sound name "glass"

tell application "Safari"
    close its front window
end tell

标签: applescript

解决方案


您从returnNumbersInString处理程序中获取了一个数字列表,但只是将列表强制转换为文本通常不会提供任何格式。一种解决方案是用于text item delimiters指定加入列表项时要使用的文本。例如,在将通知转换为文本时,您可以执行以下操作:

set tempTID to AppleScript's text item delimiters
set AppleScript's text item delimiters to ", "
set theNums to returnNumbersInString(myVar) as text
set AppleScript's text item delimiters to tempTID

推荐阅读