【问题标题】:Cannot gsub UTF-8 symbols不能 gsub UTF-8 符号
【发布时间】:2015-03-20 13:43:05
【问题描述】:

我有一个 UTF-8 字符串,需要 1)gsub 特殊符号,2)将整个数据帧转换为“正常”(ASCII?)编码。但是,我无法在其上运行 gsub - 没有捕捉到字符串。 我在French 语言环境中工作(尝试过 UTF-8),但没有获得批准。 无法为您提供完整的数据集,但会在此处发布几个字符串。

  DataFrame = read.csv("SLD_products_FullData.csv",header=F,sep=",",encoding = "UTF-8")
  title = DataFrame$title

这就是标题在控制台中的样子:

"Campbell’s Gravy and General Mills • Cheerios"

在查看器中:

Campbell’s Gravy and General Mills • Cheerios"   

尝试过(各种 perl、固定等):

gsub("’","'",title)
gsub("•","-",title)

甚至尝试过gsub("’","'",title)。没有运气。

Encoding(title)
[1] "UTF-8"

有什么建议吗?谢谢!!

标签: r utf-8 gsub


【解决方案1】:
title <- "Campbell’s Gravy and General Mills • Cheerios"
Encoding(title) 
#In your case it should be UTF-8

#iconvlist() to list possible encodings
#iconv to change encoding from latin1 to UTF-8
title <- iconv(title, "latin1", "UTF-8")
Encoding(title)
[1] "UTF-8"

#Apply Native encoding on the vector    
title <- enc2native(title)
Encoding(title)
[1] "latin1"

#Apply UTF8 encoding on the vector  
title <- enc2utf8(title)
Encoding(title)
[1] "UTF-8"

# Force a change in the encoding
Encoding(title) <- "latin1"
Encoding(title)
[1] "latin1"

title <- enc2utf8(title)
title2 <- gsub("•","-",title)
title2 <- gsub("’","'",title2)
title2
[1] "Campbell's Gravy and General Mills - Cheerios"

Encoding(title2)
[1] "unknown"

title2 <- gsub("(*UCP)(*UTF)•","--",title, perl= TRUE)
title2 <- gsub("(*UCP)(*UTF)’","'",title2, perl= TRUE)
title2
[1] "Campbell's Gravy and General Mills -- Cheerios"
Encoding(title2)
[1] "unknown"

“未知”是除 latin1、UTF-8 或字节之外的任何其他编码。 See

【讨论】:

  • 我试过了。这是代码的一部分:print(title[8]) print(Encoding(title[8])) title2 &lt;- gsub("’","-",title[8]) print(title2) 结果是:[1] "Campbell’s Gravy" [1] "UTF-8" [1] "Campbell’s Gravy"
  • P.S.如何将插入符号结尾放在评论中,使评论中的代码看起来像答案中的代码?
  • 也许:title2
猜你喜欢
  • 2012-01-14
  • 2012-03-07
  • 2013-07-06
  • 1970-01-01
  • 2011-07-17
  • 2017-10-28
  • 1970-01-01
  • 1970-01-01
  • 2014-08-06
相关资源
最近更新 更多