2010-12-01 255 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