Applescript循环解析CSV并注入值

时间:2016-06-04 05:19:15

标签: loops csv applescript

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

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*)

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

1 个答案:

答案 0 :(得分:2)

如果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)