R中的特殊字符

Tyl*_*ker 3 r

我正在努力能够将对话的成绩单读入R.然而,我遇到了一些特殊字符,例如卷曲引号en和em破折号等.通常我首先用微软产品替换这些特殊字符replace.通常我用纯文本替换特殊字符,但在某些情况下希望用其他字符替换它们(即我用"{替换"}).这很繁琐,并不总是彻底.如果我可以将原稿转录成R,然后使用Encoding将其编码切换为可识别的unicode格式,我可以将gsub它们取出并用纯文本版本替换它们.但是文件是以某种我不理解的方式读入的.这是我的数据可能是什么的xlsx:

http://dl.dropbox.com/u/61803503/test.xlsx

这是.xlsx文件中的内容

text                              num
“ ” curly quotes                    1
en dash (–) and the em dash (—)     2
‘ ’ curly apostrophe-ugg            3
…  ellipsis are uck in R            4
Run Code Online (Sandbox Code Playgroud)

这可以通过以下方式读入R:

URL <- "http://dl.dropbox.com/u/61803503/test.xlsx"
library(gdata) 
z <- read.xls(URL, stringsAsFactors = FALSE) 
Run Code Online (Sandbox Code Playgroud)

结果是:

                                 text num
1                “ †curly quotes    1
2 en dash (–) and the em dash (—)   2
3        ‘ ’ curly apostrophe-ugg   3
4          …  ellipsis are uck in R   4
Run Code Online (Sandbox Code Playgroud)

所以我尝试使用Encoding转换为Unicode:

iconv(z[, 1], "latin1", "UTF-8")
Run Code Online (Sandbox Code Playgroud)

这给出了:

[1] "â\u0080\u009c â\u0080\u009d curly quotes"                "en dash (â\u0080\u0093) and the em dash (â\u0080\u0094)"
[3] "â\u0080\u0098 â\u0080\u0099 curly apostrophe-ugg"        "â\u0080¦  ellipsis are uck in R"     
Run Code Online (Sandbox Code Playgroud)

这使得gsubing不那么有用.

我该怎么做才能将这些特殊字符转换为可区分的unicode,以便我可以适当地编写它们?为了更明确,我希望z[1, 1]阅读:

\u201C 2\u01D curly quotes
Run Code Online (Sandbox Code Playgroud)

为了更清楚地表达我想要的结果,我将从维基百科的网页上搜索表格:http://en.wikipedia.org/wiki/Quotation_mark_glyphs并使用unicode参考图表来适当地替换字符.所以我需要字符是unicode或一些标准格式,我可以系统地通过并替换字符.也许它已经存在,而我却想念它.

PS我不将文件保存为.csv或纯文本,因为特殊字符被替换为?因此使用read.xls 我没有附加到文件中的任何特定读取方法(即read.xls)如果你有更好的选择.

A5C*_*2T1 9

也许这会有所帮助(明天我可以访问一台Windows机器,如果SO没有得到你的答案,可能会更多地使用它.)

在我的Linux系统上,当我执行以下操作时:

iconv(z$text, "", "cp1252")
Run Code Online (Sandbox Code Playgroud)

我明白了:

[1] "\x93 \x94 curly quotes"                "en dash (\x96) and the em dash (\x97)"
[3] "\x91 \x92 curly apostrophe-ugg"        "\x85  ellipsis are uck in R"  
Run Code Online (Sandbox Code Playgroud)

这不是UTF,但(我相信)ISO hex实体.尽管如此,如果你能够达到这一点,那么你应该能够gsub按照你想要的方式使用.

有关转换,请参阅此页面(特别是保留部分).

更新

您也可以尝试转换为不具有这些字符的编码,例如ASCII并设置sub"byte".在我的机器上,这给了我:

iconv(z$text, "", "ASCII", "byte")
# [1] "<e2><80><9c> <e2><80><9d> curly quotes"               
# [2] "en dash (<e2><80><93>) and the em dash (<e2><80><94>)"
# [3] "<e2><80><98> <e2><80><99> curly apostrophe-ugg"       
# [4] "<e2><80><a6>  ellipsis are uck in R"   
Run Code Online (Sandbox Code Playgroud)

它很难看,但它UTF-8(e2, 80, 9c)是一个正确的卷曲引号(我相信,每个字符都是带角度的括号中的三个值).您可以在此站点上找到可通过标点符号名称进行搜索的转换.

  • 很抱歉刚回来这是一个很难解决的问题。您的第二个解决方案适用于我的问题。 (2认同)