【问题标题】:Writing Russian text to txt file将俄语文本写入 txt 文件
【发布时间】:2010-12-01 21:36:27
【问题描述】:

我正在尝试将一些俄语文本或西里尔文文本写入 .txt 文件。我可以成功地这样做,但是当我打开文件时,代替文本写入的所有内容都是一堆问号。我当时认为这是一个编码问题,但在该区域找不到任何帮助。我写了一个小脚本来演示这个问题。

do shell script "> $HOME/Desktop/Russian\\ Text.txt"
set text_path to ((path to home folder) & "Desktop:Russian Text.txt" as string) as alias

set write_text to "Привет"

tell application "Finder"
    write write_text to text_path
    set read_text to text of (read text_path)
end tell

如果有人对为什么会发生这种情况有任何想法,请告诉我。谢谢。

【问题讨论】:

  • 你用什么打开文件?听起来像是向我显示文件的问题。它没有检测字符集,而是用问号代替它无法显示的字符。

标签: character-encoding applescript


【解决方案1】:

我无法回答你的问题。您的代码中确实有很多 applescript 编码问题,但没有一个会导致您的问题。 Applescript 可以很好地处理非 ascii 文本。我有时会用丹麦语写作,它很管用。但是,当我使用俄语尝试我的脚本时,我得到了与您相同的结果。我无法解释为什么。只是为了让您可以看到读取和写入文件的正确语法,这是我的代码。请注意,我不使用 Finder 来执行这些任务,还请注意我如何设置输出文件的路径...

set outpath to (path to desktop as text) & "danish.txt"
set theText to "primær"

-- write the file
set openFile to open for access file outpath with write permission
write theText to openFile
close access openFile

-- read the file
set readText to read file outpath

更新:我找到了您问题的答案。似乎如果您将 utf-16 字节顺序标记 (BOM) 写入文件,那么它对于俄语可以正常工作。因此,我制作了两个处理程序,以便您可以读取和写入这些文件...

set filePath to (path to desktop as text) & "russian.txt"
set theText to "Привет"

write_UnicodeWithBOM(filePath, theText, true)
read_UnicodeWithBOM(filePath)

on write_UnicodeWithBOM(filePath, theText)
    try
        set openFile to open for access file (filePath as text) with write permission
        write (ASCII character 254) & (ASCII character 255) to openFile starting at 0
        write theText to openFile starting at eof as Unicode text
    end try
    try
        close access openFile
    end try
end write_UnicodeWithBOM

on read_UnicodeWithBOM(filePath)
    read file (filePath as text) as Unicode text
end read_UnicodeWithBOM

【讨论】:

  • 谢谢。这就像一个魅力。也感谢您向我展示正确的语法。当你从这里和那里学习时,很难知道你是否正在写它。再次感谢。
猜你喜欢
  • 2016-11-10
  • 2011-08-10
  • 1970-01-01
  • 1970-01-01
  • 2016-11-10
  • 2016-01-08
  • 2013-06-03
  • 1970-01-01
  • 2011-03-13
相关资源
最近更新 更多