Applescript для извлечения файлов RTF с неработающей гиперссылкой - PullRequest
0 голосов
/ 10 января 2019

Я пытаюсь извлечь как гиперссылки, так и обычный текст из папки с 450+ файлами RTF. Каждый файл имеет одинаковую структуру.

Я использую следующий Applescript, который отлично работает и правильно декодирует файл в окне результатов.

Однако я получаю эту ошибку, и у меня недостаточно опыта, чтобы ее исправить.

ошибка "- [NSURL writeToURL: атомарно: кодировка: ошибка:]: нераспознано селектор отправлен на экземпляр 0x7fa6f527c7f0 "номер -10000

Это скрипт, который я нашел в интернете:

use AppleScript version "2.4" -- Yosemite (10.10) or later

use framework "Foundation"

use framework "AppKit"

use scripting additions

set theFolder to choose folder -- choose the folder containing the .rtf files

tell application id "com.apple.finder" -- Finder

    set theFiles to every file of theFolder as alias list

end tell

repeat with aFile in theFiles

    if (aFile as text) ends with ".rtf" then

        set theURL to (current application's NSURL's fileURLWithPath:(POSIX path of aFile))

        set {attString, theError} to (current application's NSAttributedString's alloc()'s initWithURL:theURL options:(missing value) documentAttributes:(missing value) |error|:(reference))

        -- get elngth so we can start from the end
        set start to (attString's |length|()) - 1

        -- make plain string copy to work on
        set theString to attString's |string|()'s mutableCopy()
        repeat
            -- find link

            set {aURL, theRange} to (attString's attribute:(current application's NSLinkAttributeName) atIndex:start effectiveRange:(reference))

            if aURL is not missing value then
                -- get linked text
                set linkText to (theString's substringWithRange:theRange)
                if (aURL's |scheme|()'s isEqualToString:"mailto") then -- email address

                    set newLink to aURL's resourceSpecifier()

                else if (linkText's containsString:"This Site") then -- resource specifier, remove //

                    set newLink to (aURL's resourceSpecifier()'s substringFromIndex:2)

                else -- full URL

                    set newLink to aURL's absoluteString()
                end if

                -- replace link
                (theString's replaceCharactersInRange:theRange withString:newLink)

            end if

            set start to (location of theRange) - 2

            if start < 0 then exit repeat

        end repeat

        set newFile to (theURL's URLByDeletingPathExtension()'s URLByAppendingPathExtension:"text")

        (newFile's writeToURL:theURL atomically:true encoding:(current application's NSUTF8StringEncoding) |error|:(missing value))

    end if

end repeat

Любая помощь будет принята с благодарностью.

Это структура файлов, практически идентичных для каждого из них в папке:

Этот сайт (с гиперссылкой)

Дата подачи

12 декабря 2018

Дата уведомления

1 октября 2019

Дата события

25 октября 2019

номер для отслеживания

SIFF4964

    Email  (with Hyperlink)

    Website  (Hyperlink)

Я надеюсь получить простой текстовый файл как таковой

Site.com

Дата подачи

12 декабря 2018

Дата уведомления

1 октября 2019

Дата события

25 октября 2019

номер для отслеживания

SIFF4964

address@site.com

site.com

Спасибо

1 Ответ

0 голосов
/ 10 января 2019

В ошибке четко указано, что writeToURL:atomically:encoding:error не принадлежит NSURL.

Это просто опечатка, вы хотите записать замененную строку на диск, а не URL

(theString's writeToURL:newFile atomically:true encoding:(current application's NSUTF8StringEncoding) |error|:(missing value))

PS: Пожалуйста, не будь неблагодарным, Шейн проделал большую работу для тебя на MacScripter ?

...