applescript - 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®ion=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
解决方案
您从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
推荐阅读
- shell - 有没有办法读取由制表符分隔的键值对?
- r - R - ggplot scale_x_date 图中日期不正确
- vb6 - 有没有办法在树视图中实现像“BeforeSelect”这样的事件?
- python - 数据框:将一行复制到另一行,同时保持不同的 dtypes 列
- sql - 两个表之间的链接
- ios - 更改 tableView 单元格的高度不起作用
- data-structures - 粉碎链表节点
- gitlab - 全文搜索所有 git 存储库 (gitlab)
- javascript - 如何在组件函数内动态生成用户定义的类对象
- php - 使用 Laravel 创建论坛但遇到 Angular 问题