Использование cat для записи неанглийских символов в файл .html (в R)

Вот код, показывающий проблему:

myPath = getwd()
cat("abcd", append = T, file =paste(myPath,"temp1.html", sep = "\\")) # This is fine
cat("<BR/><BR/><BR/>", append = T, file =paste(myPath,"temp1.html", sep = "\\")) # This is fine
cat("שלום", append = F, file =paste(myPath,"temp1.html", sep = "\\")) # This text gets garbled when the html is opened using google chrome on windows 7.
cat("שלום", append = F, file =paste(myPath,"temp1.txt", sep = "\\")) # but if I open this file in a text editor - the text looks fine

# The text in the HTML folder would look as if I where to run this in R:
(x <- iconv("שלום", from = "CP1252", to = "UTF8") )
# But if I where to try and put it into the file, it wouldn't put anything in:
cat(x, append = T, file =paste(myPath,"temp1.html", sep = "\\")) # empty

Изменить: я также пытался использовать следующую кодировку (без успеха)

ff <-file(paste(myPath,"temp1.html", sep = "\\"), encoding="CP1252")
cat("שלום", append = F, file =ff)
ff<-file(paste(myPath,"temp1.html", sep = "\\"), encoding="utf-8")
cat("שלום", append = F, file =ff)
ff<-file(paste(myPath,"temp1.html", sep = "\\"), encoding="ANSI_X3.4-1986")
cat("שלום", append = F, file =ff)
ff<-file(paste(myPath,"temp1.html", sep = "\\"), encoding="iso8859-8")
cat("שלום", append = F, file =ff)

Какие-либо предложения? Спасибо.


person Tal Galili    schedule 20.09.2011    source источник
comment
Похоже, тебе нужно немного поспать... =) Sys.sleep(sample(3600 * .5:8.5, 1))   -  person aL3xa    schedule 20.09.2011
comment
Взгляните на этот вопрос о сохранении csv с кодировкой UTF-8.   -  person Marek    schedule 20.09.2011
comment
Привет, Марек, когда я пытаюсь использовать его, я получаю текст, превращающийся в \xf9\xec\xe5\xed   -  person Tal Galili    schedule 20.09.2011


Ответы (3)


Ваш код немного избыточен. Является ли temp1.txt в строке 5 опечаткой (.html)? В любом случае, возможно, вам следует установить charset в теге <meta>.

Возьмите это в качестве примера:

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
</head>
<body>
<%
cat("abcd")
cat("<BR/><BR/><BR/>")
cat("שלום")
cat("שלום")
(x <- iconv("שלום", from = "CP1252", to = "UTF8") )
cat(x)
-%>
</body>
</html>

Это код brew, поэтому, если вы наберете его brew, вы получите правильный ответ. Короче говоря, ключевое слово было charset.

person aL3xa    schedule 20.09.2011

Проблема не в R (R правильно выдает вывод в кодировке UTF-8)… просто ваш веб-браузер предполагает неправильную кодировку при отсутствии явно указанной кодировки. Вместо этого просто используйте следующий фрагмент (изнутри R):

<html>
    <head>
        <meta http-equiv="content-type" content="text/html; charset=utf-8">
    </head>
    <body>
        שלום
    </body>
</html>

Это указывает правильную кодировку (UTF-8) и, следовательно, заставляет браузер правильно передавать следующий текст.

person Konrad Rudolph    schedule 20.09.2011

Попробуйте так

cat("abcd", file = (con <- file("temp1.html", "w", encoding="UTF-8"))); close(con)
person George Dontas    schedule 20.09.2011
comment
Спасибо gd047, но это не работает. Это оставляет меня с этим: שלו×. Вместо שלום - person Tal Galili; 20.09.2011