Как автоматизировать поиск и замену в файле Numbers на основе предопределенного основного списка?
Например, я хочу найти и заменить все:
Несколько мыслей/ожиданий рабочего процесса:
Я не совсем уверен, как вы отформатировали документ Numbers или как именно вы хотите сохранить основной список элементов поиска и замены или, однако , где следующий пример кода AppleScript настроен для демонстрации использования основного списка Поиск и замена элементов в виде отдельной таблицы на листе в документе Numbers , состоящей из двух столбцов и необходимого количества строк .
На изображениях ниже показаны листы , основной список элементов поиска и замены , а также лист 1 до и после . Данные упрощены, но суть в том, что они работают для быстрого поиска и замены пар элементов «Найти и заменить» в основном списке .
Это будет намного быстрее, чем любой ручной процесс для достижения той же цели.
Обратите внимание, что в закодированном виде предполагается, что в ячейках нет формул , и они отформатированы как текст.
Пример кода AppleScript :
tell application "Numbers"
tell front document
-- # Get the Find & Replace list.
set theFindReplaceList to ¬
the formatted value of ¬
the cells of the rows 2 thru -1 of ¬
table "Find & Replace" of ¬
sheet "Master List" whose ¬
value is not missing value
-- # Clean up the List removing empty cells and rows
-- # so there are only pairs of find/replace items.
set theFindReplaceListItems to {}
repeat with aListItem in theFindReplaceList
if the length of aListItem is 2 then ¬
copy aListItem to the end of theFindReplaceListItems
end repeat
copy theFindReplaceListItems to theFindReplaceList
-- ### Find & Replace ###
if the name of active sheet is not "Master List" then
-- # For each table of the active sheet.
repeat with i from 1 to the count of the tables of the active sheet
-- # For each Find & Replace pair.
repeat with thisListItem in theFindReplaceList
-- # For every cell containing the FIND text.
set theReplaceCellsList to the (cells of table i of sheet 1 ¬
whose formatted value contains item 1 of thisListItem)
-- # Replace it with the REPLACE text.
-- # Uncomment 'considering case' and 'end considering'
-- # for case senstive find/replace operations.
--considering case
repeat with aCell in theReplaceCellsList
set the value of aCell to my findAndReplaceInCellValue(formatted value of aCell, ¬
item 1 of thisListItem, item 2 of thisListItem)
end repeat
--end considering
end repeat
end repeat
tell table 1 of active sheet to set selection range to range "A1"
end if
end tell
end tell
-- ## Handler ##
on findAndReplaceInCellValue(theFormatedCellValue, theFindValue, theReplaceValue)
set AppleScript's text item delimiters to theFindValue
set theTextItems to every text item of theFormatedCellValue
set AppleScript's text item delimiters to theReplaceValue
set theFormatedCellValue to theTextItems as string
set AppleScript's text item delimiters to ""
return theFormatedCellValue
end findAndReplaceInCellValue
Примечания:
Хотя закодированный пример кода AppleScript использует лист в целевом документе для своих элементов «Найти и заменить» , тем не менее, его можно закодировать для использования и внешнего источника, например другого документа Numbers .
В обоих примерах кода лист основного списка не затрагивается операциями поиска/замены.
Операции поиска/замены нечувствительны к регистру . Если вам нужен поиск/замена с учетом регистра , раскомментируйте операторыconsidering case
и в примере кода AppleScript .end considering
Как закодировано, операции поиска/замены действуют на ячейки , содержащие значение текста FIND и все остальное в ячейке . Если вы хотите ограничиться ячейками , в которых есть только текст НАЙТИ и ничего больше, то:
Изменять:
set theReplaceCellsList to the (cells of table i of aSheet ¬
whose formatted value contains item 1 of thisListItem)
К:
set theReplaceCellsList to the (cells of table i of aSheet ¬
whose formatted value is item 1 of thisListItem)
Пример кода AppleScript можно использовать в Automator Service/Quick Action с помощью действия «Запустить AppleScript» и назначить сочетание клавиш в «Системных настройках» > «Клавиатура » > «Ярлыки» > « Службы» или использовать с любым сторонним приложением , которое может запускать сценарии AppleScript и т. д.
Пример кода AppleScript :
tell application "Numbers"
tell front document
-- # Get the Find & Replace list.
set theFindReplaceList to ¬
the formatted value of ¬
the cells of the rows 2 thru -1 of ¬
table "Find & Replace" of ¬
sheet "Master List" whose ¬
value is not missing value
-- # Clean up the List removing empty cells and rows
-- # so there are only pairs of find/replace items.
set theFindReplaceListItems to {}
repeat with aListItem in theFindReplaceList
if the length of aListItem is 2 then ¬
copy aListItem to the end of theFindReplaceListItems
end repeat
copy theFindReplaceListItems to theFindReplaceList
-- ### Find & Replace ###
-- # For each sheet in the document.
repeat with aSheet in (sheets whose name is not "Master List")
-- # For each table of the sheet.
repeat with i from 1 to the count of the tables of aSheet
-- # For each Find & Replace pair.
repeat with thisListItem in theFindReplaceList
-- # For every cell containing the FIND text.
set theReplaceCellsList to the (cells of table i of aSheet ¬
whose formatted value contains item 1 of thisListItem)
-- # Replace it with the REPLACE text.
-- # Uncomment 'considering case' and 'end considering'
-- # for case senstive find/replace operations.
--considering case
repeat with aCell in theReplaceCellsList
set the value of aCell to my findAndReplaceInCellValue(formatted value of aCell, ¬
item 1 of thisListItem, item 2 of thisListItem)
end repeat
--end considering
end repeat
end repeat
tell table 1 of active sheet to set selection range to range "A1"
end repeat
end tell
end tell
-- ## Handler ##
on findAndReplaceInCellValue(theFormatedCellValue, theFindValue, theReplaceValue)
set AppleScript's text item delimiters to theFindValue
set theTextItems to every text item of theFormatedCellValue
set AppleScript's text item delimiters to theReplaceValue
set theFormatedCellValue to theTextItems as string
set AppleScript's text item delimiters to ""
return theFormatedCellValue
end findAndReplaceInCellValue
Таблица «Найти и заменить» всегда должна состоять из двух столбцов , однако сценарий запрограммирован так, чтобы обрабатывать только строки , содержащие как элемент поиска , так и элемент замены .
Примечание. Пример кода AppleScript является именно этим и без какой-либо включенной обработки ошибок не содержит какой-либо дополнительной обработки ошибок , которая может быть уместной. Пользователь несет ответственность за добавление любой обработки ошибок , которая может быть уместной, необходимой или желательной. Посмотрите оператор try и оператор error в Руководстве по языку AppleScript . См. также Работа с ошибками . Кроме того , при необходимости может потребоваться использование команды задержки между событиями, например , при значении задержки delay 0.5
установить соответствующим образом.
Пока это то, что у меня есть. Я знаю, что ответ неполный, но вы можете увидеть, правильный ли это путь для вас. Я отредактирую, когда закончу.
Код:
on run {input, parameters}
tell application "Numbers"
activate
tell front document
tell sheet "Master" -- use info from master sheet
tell table 1
set FIND to value of cell "B2" as text
set REPLACE to value of cell "C2" as text
end tell
end tell
end tell
tell document 1 of application "Numbers"
set active sheet to sheet 1 -- work data from Sheet 1
end tell
end tell
tell application "System Events"
key code 3 using {command down} -- Command+F to search/replace
delay 0.15
set the clipboard to FIND
delay 3 -- enough time to perform search (should be tweaked for large documents)
key code 9 using {command down} -- paste data to find
delay 0.8
key code 48 -- tab
delay 0.8
set the clipboard to REPLACE
delay 0.8
key code 9 using {command down} -- paste data to replace
delay 0.8
key code 48 -- tab
delay 0.8
key code 49 -- space (press "replace all" button)
end tell
end run
Следующие шаги:
bmike