2010-12-01 253 views
2

我正在尝试将一些俄文文本或西里尔文本写入.txt文件。我可以成功地做到这一点,但是当我打开文件时,所有写入文本的地方都是一堆问号。我认为这是一个编码问题,但在该领域找不到任何帮助。我写了一个脚本来演示这个问题。将俄文文本写入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 

如果任何人有任何想法,为什么发生这种情况请让我知道。谢谢。

+0

您打开该文件时用的是什么?听起来像什么显示文件给我的问题。它没有检测到字符集,而是将问号替换为无法显示的字符。 – Brad 2010-12-01 21:53:18

回答

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 
+0

谢谢。这工作像一个魅力。也感谢您向我展示正确的语法。当你在这里和那里学习时,很难知道你是否正在编写它。再次感谢。 – piercelayne 2010-12-13 09:04:34