2016-06-04 2 views
0

Я пытаюсь пропустить каждое значение, разделенное запятыми, в файле и каждый элемент подвергается серии действий. По существу, рабочий процесс заключается в следующем:Цикл 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 

EDIT:

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

Что разделителем я должен использовать в этом случае?

ответ

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 читает текстовую строку раздельно (она рассматривает LF, CR и CRLF).

set strFileContents to paragraphs of (read pathInputFile) 
+0

похоже, что мой файл csv содержит цитаты, к сожалению - как бы вы изменили свой подход? – pepe

+0

В поле ** ** ** включены кавычки или только несколько? Я обновил ответ на все поля «все». – vadian

+0

THX так много для вашей помощи. Я немного озадачен этим: в OS X, когда я «сохраняю как» в Excel как любое множество CSV (CSV, CSV, CSV, MS-DOS CSV и т. Д.), А затем открываю файл в TextEdit или другом чистом редакторе кода, элементы фактически не разделяются запятыми, а отображаются как 1 в каждой строке. Будет ли это проблемой для использования вашего предложения? – pepe

Смежные вопросы