【问题标题】:Read textfile into list in Applescript将文本文件读入 Applescript 中的列表
【发布时间】:2012-04-08 17:32:56
【问题描述】:

我尝试创建一个读取文本文件并将内容放入列表的 AppleScript。该文件是一个简单的文本文件,其中每一行如下所示:example-"example"

第一个是文件名,另一个是文件夹名。

这是我的代码:

set listOfShows to {}
set theFile to readFile("/Users/anders/Desktop/test.txt")
set Shows to read theFile using delimiter return
repeat with nextLine in Shows
    if length of nextLine is greater than 0 then
        copy nextLine to the end of listOfShows
    end if
end repeat
choose from list listOfShows


on readFile(unixPath)
    set foo to (open for access (POSIX file unixPath))
    set txt to (read foo for (get eof foo))
    close access foo
    return txt
end readFile

当我运行该输出时,我得到了这个:

error "Can not change \"Game.of.Thrones-\\\"Game Of \" to type file." number -1700 from "Game.of.Thrones-\"Game Of " to file"

我的列表如下所示:Game.of.Thrones-“权力的游戏”和另外两行类似的内容。

【问题讨论】:

    标签: file text applescript


    【解决方案1】:

    错误是您试图读取文件的内容(您读取的第一个文件)作为文件。获取文本的段落会在返回/换行边界处将其分开,这通常比尝试猜测文件中使用的行尾字符更好。

    在读取文件时,您也不需要整个 open for access,因此您的脚本可以简化为

    set listOfShows to {}
    set Shows to paragraphs of (read POSIX file "/Users/anders/Desktop/test.txt")
    repeat with nextLine in Shows
        if length of nextLine is greater than 0 then
            copy nextLine to the end of listOfShows
        end if
    end repeat
    choose from list listOfShows
    

    【讨论】:

    • 它在我的输出中仍然只读取“Game.of.Thrones-\”Game Of”,我现在没有收到任何错误。
    • 我现在尝试在文本文件中使用 text: 1text, 2text ... 5text。结果是 1text, 2text, 3text, 4text, 5。不是 5text
    • 脚本只获取文件的每一行(由换行符分隔,例如回车)并将其放入列表中 - 这不是您问的吗?不知道为什么文件不会被完全读取,除非您没有使用普通的读取命令并且正在使用分隔符或读取的字符数。
    • 我只想读取文件中的每一行。但是由于某种原因它不能输出所有内容?我会尝试更多,你让我以正确的方式,谢谢:)
    • 问题是它只占用文本文件中的前 23 个字符。不知道是什么原因造成的?
    【解决方案2】:

    read 默认使用 MacRoman,因此它会混淆 UTF-8 文件中的非 ASCII 字符,除非您添加 as «class utf8»。 (as Unicode text 是 UTF-16。)

    paragraphs of (read POSIX file "/tmp/test.txt") as «class utf8»
    

    paragraphs of 也适用于 CRLF 和 CR 行尾。这不是,但如果它是空的,它会忽略最后一行:

    read POSIX file "/tmp/test.txt" as «class utf8» using delimiter linefeed
    

    【讨论】:

      【解决方案3】:
      set milefile to ((path to desktop as text) & "Alert.txt")
      set theFileContents to (read file milefile)
      display dialog theFileContents
      

      【讨论】:

      • 虽然此代码可能会回答问题,但提供有关 why 和/或 如何 回答问题的额外上下文将显着改善其长期价值。请edit你的答案添加一些解释。
      【解决方案4】:

      AppleScript 的语言参考第 120 页所述:

      紧接在上一段结尾后的第一个字符或文本开头之后并以回车符 (\r)、换行符 (\n)、回车符/换行符对结尾的一系列字符(\r\n),或文本的结尾。不支持 Unicode“段落分隔符”字符 (U+2029)。

      因此,U+8232 被忽略,AppleScript 从文件中返回整个文本……

      U+8232 在 TextEdit 中用作 CR 字符...

      【讨论】:

      • 虽然 ASLR 提到 U+2029 不受支持,但它却忽略了 Applescript 也不支持的 U+2028。它们分别是段落分隔符和行分隔符。如文本所示,它们是 Unicode 字符,除了 8232 和 8233 实体之外的浏览器似乎没有得到很好的支持。见en.wikipedia.org/wiki/Unicode#Newlines
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-20
      • 1970-01-01
      • 2018-12-03
      • 1970-01-01
      • 2012-06-22
      • 1970-01-01
      相关资源
      最近更新 更多