Using “cat” to write non-English characters into a .html file (in R)

前端 未结 3 1932
野的像风
野的像风 2021-01-21 08:33

Here is the code showing the problem:

myPath = getwd()
cat(\"abcd\", append = T, file =paste(myPath,\"temp1.html\", sep = \"\\\\\")) # This is fine
cat(\"
相关标签:
3条回答
  • 2021-01-21 09:02

    Try it this way

    cat("abcd", file = (con <- file("temp1.html", "w", encoding="UTF-8"))); close(con)
    
    0 讨论(0)
  • 2021-01-21 09:05

    Your code is a bit redundant. Is temp1.txt on line 5 a typo (.html)? Anyway, perhaps you should set charset within <meta> tag.

    Take this as an example:

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

    It is a brew code, so if you go ahead and brew it, you'll get correct response. Long story short, the keyword was charset.

    0 讨论(0)
  • 2021-01-21 09:07

    The problem isn’t with R (R is correctly producing UTF-8 encoded output) … it’s just that your web browser assumes the wrong encoding in the absence of an explicitly specified encoding. Just use the following snippet (from inside R) instead:

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

    This specifies a correct encoding (UTF-8), and hence causes the browser to thread the following text correctly.

    0 讨论(0)
提交回复
热议问题