【问题标题】:How can I make these visually identical strings computationally equal?如何使这些视觉上相同的字符串在计算上相等?
【发布时间】:2019-10-30 11:57:36
【问题描述】:

上下文:

我希望基于一个字符向量加入两个小标题,但在 write.csv()read.csv() 之间发生了一些事情,这使得它们不等效。在下面的表示中,str_cmp() 返回0(“匹配”),但在我的实际项目中它返回-1(字符串不可比较)。我不知道为什么会改变。

无论如何str_cmp() 对我来说用处不大,因为dplyr::left_join 加入相等的值并且不能与函数一起使用。

我如何更改这些字符串之一以使str1==str2 返回TRUE? 我需要能够为整个字符向量执行此操作,以便我可以这样做:

dplyr::left_join(tibble1,tibble2,by = c("charVector1"="charVector2") 其中charVector1charVector2 是从中提取str1str2 的列。

代表:

#DL 19/10/30
## Tryna work out why these strings aren't the same
#####################################################################

#Get strings from GitHub repo ---------------------------------------
read.table(
  "https://raw.githubusercontent.com/davelovellCARU/stringHelp/master/string1.txt"
) ->
  str1

read.table(
  "https://raw.githubusercontent.com/davelovellCARU/stringHelp/master/string2.txt"
) ->
  str2

# The strings are not equal -----------------------------------------
str1 == str2
#>       x
#> 1 FALSE
# But they look the same and the computer knows it ------------------
stringi::stri_cmp(str1, str2)
#> [1] 0

reprex package (v0.3.0) 于 2019 年 10 月 30 日创建

【问题讨论】:

  • string2.txt 采用 ANSI 编码,而 string1.txt 采用 UTF-8 无 BOM 编码。所以字符串不一样?
  • 谢谢,非常有帮助。字符串编码对我来说仍然是个谜

标签: r string stringi


【解决方案1】:

知道了!

有一个简洁的函数可以做到这一点:stringclean::replace_non_ascii(string) 我在两个字符串上运行它,现在它们是相同的。只需将其放入 mutate 中,tibbles 就会加入。

【讨论】:

  • 对于现在提到这个的任何人,该包已重命名为textclean
猜你喜欢
  • 1970-01-01
  • 2015-07-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多