Applescript 循环来解析 CSV 并注入值



我正在尝试遍历文件中的每个逗号分隔值,并让每个项目经历一系列操作。本质上,工作流程是这样的:

CSV file:
123,456,789
Workflow:
[1] Take '123'
[2] Inject '123' into a text field
[3] Click on buttons
[4] Repeat until (and including) last value in CSV

我当前的代码如下,但我无法正确循环或将当前项目注入文本字段。

你能给我任何指示吗?

set pathInputFile to (choose file with prompt "Select the CSV file" of type "csv")
set strFileContents to read pathInputFile
set parFileContents to (paragraphs of strFileContents)
set numRows to count of parFileContents
repeat with iPar from 1 to number of items in parFileContents
    set lstRow to item iPar of parFileContents
    if lstRow = "" then exit repeat -- EXIT Loop if Row is empty, like the last line
    set lstFieldsinRow to parseCSV(lstRow as text)
    ----------
    -- now I would need to pass the current value to the next block
    -- and "paste" it into the text field
    ----------
    tell application "System Events"
        tell process "App"
            set frontmost to true
            click menu item "Query Window..." of menu "Network" of menu bar 1
            click radio button "Number" of tab group 1 of window "Query"
            set focused of text field 1 of tab group 1 of window "Query" to true
            delay 0.1
            keystroke "a" using command down
            delay 0.1
            keystroke "v" using command down
            click UI element "Query" of group 4 of splitter group 1 of window "Query"
        end tell
    end tell
end repeat -- with iPar

编辑:

set pathInputFile to (choose file with prompt "Select the CSV file" of type "csv")
set strFileContents to read pathInputFile
log strFileContents
Output:
(*147782
167482
182676
185309
184119
188494*)

在这种情况下,我应该使用什么分隔符?

如果CSV是简单的CSV(没有双引号作为额外的字段分隔符),那么使用AppleScript的text item delimiters分隔项目也很简单。

set theCSV to "123,456,789"
set {TID, text item delimiters} to {text item delimiters, ","}
repeat with anItem in (get text items of theCSV)
    display dialog anItem buttons {"OK"} default button 1
end repeat
set text item delimiters to TID

如果所有字段都用双引号括起来,您可以使用这个

set theCSV to ""123","456","789""
set trimmedCSV to text 2 thru -2 of theCSV
set {TID, text item delimiters} to {text item delimiters, quote & "," & quote}
repeat with anItem in (get text items of trimmedCSV)
    display dialog anItem buttons {"OK"} default button 1
end repeat
set text item delimiters to TID

EDIT部分的数据结构似乎是行分隔的(每行一个项目),而不是真正的CSV。在这种情况下,既不需要text item delimiters也不需要重复循环。 paragraphs of读取分隔的文本行(它考虑LFCRCRLF)。

set strFileContents to paragraphs of (read pathInputFile)

最新更新