gpt4 book ai didi

r - iconv() 在给定具有特定特殊字符的字符串时返回 NA

转载 作者:行者123 更新时间:2023-12-05 03:39:16 25 4
gpt4 key购买 nike

我正在尝试将输入文件的一些字符串从 UTF8 转换为 ASCII。对于我给它的大多数字符串,使用 iconv() 转换效果非常好。但是在其中一些上,它返回 NA。虽然手动修复文件中的问题似乎是最简单的选择,但不幸的是,我目前根本无法使用它。

我已经为我的问题做了一个可重现的例子,但我们假设我必须想出一种方法让 iconv() 以某种方式转换 s1 中的字符串,并且没有得到 NA

这是可重现的例子:

s1 <- "Besançon" #as read from an input file I cannot modify
s2 <- "Paris"
s3 <- "Linköping"
s4 <- "Besançon" #Manual input for testing

s1 <- iconv(s1, to='ASCII//TRANSLIT')
s2 <- iconv(s2, to='ASCII//TRANSLIT')
s3 <- iconv(s3, to='ASCII//TRANSLIT')
s4 <- iconv(s4, to='ASCII//TRANSLIT')

我得到以下输出:

> s1
[1] NA
> s2
[1] "Paris"
> s3
[1] "Link\"oping"
> s4
[1] "Besancon"

在研究代码之后,我发现现在从输入文件中完全复制的条目“Besançon”中有问题。当我自己手动输入时,问题就解决了。由于我根本无法修改输入文件,您认为确切的问题是什么?您是否知道如何解决它?

提前致谢

编辑:

仔细观察后,第一行的字符有些奇怪。它似乎被SO的格式带走了。但是要重现它,我能给出的最好的就是这两张描述它的图像。第一张图片将我的光标放在 # 之前第二张图片是在按删除键后,应该删除空白...结果是删除了“。所以那里肯定有一些奇怪的东西。

enter image description here

enter image description here

最佳答案

事实证明,使用 sub='' 实际上解决了问题,尽管我不太确定为什么。

iconv(s1, to='ASCII//TRANSLIT', sub='')

来自文档sub

character string. If not NA it is used to replace any non-convertiblebytes in the input. (This would normally be a single character, butcan be more.) If "byte", the indication is "" with the hex code ofthe byte. If "Unicode" and converting from UTF-8, the Unicode point inthe form "<U+xxxx>".

所以我最终发现字符串中有一个我无法转换(也看不到)的字符,使用 sub 是消除它的一种方法。我仍然不确定这个角色是什么。但是问题解决了。

关于r - iconv() 在给定具有特定特殊字符的字符串时返回 NA,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68618922/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com