将俄语文本写入txt文件

时间:2010-12-01 21:36:27

标签: character-encoding applescript

我正在尝试将一些俄语文本或西里尔文本写入.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

如果有人对于为什么会这样做有任何想法,请告诉我。谢谢。

1 个答案:

答案 0 :(得分:5)

我无法回答你的问题。您的代码中确实存在大量的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