【问题标题】:Using "cat" to write non-English characters into a .html file (in R)使用“cat”将非英文字符写入 .html 文件(在 R 中)
【发布时间】:2011-11-20 23:24:52
【问题描述】:

这是显示问题的代码:

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)

有什么建议吗?谢谢。

【问题讨论】:

  • 看来你需要睡觉了... =) Sys.sleep(sample(3600 * .5:8.5, 1))
  • 嗨 Marek,当我尝试使用它时,我得到的文本变成了 "\xf9\xec\xe5\xed"

标签: html r utf-8 hebrew cat


【解决方案1】:

您的代码有点多余。第 5 行的 temp1.txt 是错字吗(.html)?无论如何,也许你应该在&lt;meta&gt; 标签内设置charset

以此为例:

<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

【讨论】:

    【解决方案2】:

    问题不在于 R(R 正确地生成 UTF-8 编码输出)……只是您的 Web 浏览器在没有明确指定的编码的情况下假定了错误的编码。只需使用以下 sn-p(来自 R 内部):

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

    这指定了正确的编码 (UTF-8),从而使浏览器正确地串接以下文本。

    【讨论】:

      【解决方案3】:

      试试这个方法

      cat("abcd", file = (con <- file("temp1.html", "w", encoding="UTF-8"))); close(con)
      

      【讨论】:

      • 感谢 gd047,但它不起作用。它给我留下了这个:שלו×。而不是 שלום
      猜你喜欢
      • 1970-01-01
      • 2016-11-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-09-01
      相关资源
      最近更新 更多