【问题标题】:Stringi/stringr pattern behave differently if function is sourced in R如果函数来源于 R,Stringi/stringr 模式的行为会有所不同
【发布时间】:2018-02-28 10:21:18
【问题描述】:

我现在使用stringi 包有一段时间了,一切正常。

我最近想将一些正则表达式放入一个函数中并将该函数存储在一个单独的文件中。如果函数是从脚本加载的,那么代码就可以正常工作,但是当它被获取时,我没有得到预期的结果。

这里是重现问题的代码:

clean <- function(text){
  stri_replace_all_regex(str = text, 
                         pattern = "(?i)[^a-zàâçéèêëîïôûùüÿñæœ0-9,\\.\\?!']",
                         replacement = " ")
}
text <- "A sample text with some french accent é, è, â, û and some special characters |, [, ( that needs to be cleaned."
clean(text) # OK
[1] "A sample text with some french accent é, è, â, û and some special characters  ,  ,   that needs to be cleaned."
source(clean.r)
clean(text) # KO
[1] "A sample text with some french accent  ,  ,  ,   and some special characters  ,  ,   that needs to be cleaned."

我想删除不是字母、重音字母和标点符号?!,. 的所有内容。

如果函数直接加载到脚本中,代码就可以正常工作。如果它是有源的,那么它会给出不同的结果。

我也尝试过使用stringr,但我遇到了同样的问题。我的文件以 UTF-8 编码保存。

我不明白为什么会这样,非常感谢任何帮助。

谢谢。

R version 3.4.1 (2017-06-30)
Platform: x86_64-w64-mingw32/x64 (64-bit)
Running under: Windows >= 8 x64 (build 9200)

Matrix products: default

locale:
[1] LC_COLLATE=French_France.1252  LC_CTYPE=French_France.1252   
[3] LC_MONETARY=French_France.1252 LC_NUMERIC=C                  
[5] LC_TIME=French_France.1252    

attached base packages:
[1] stats     graphics  grDevices utils     datasets  methods   base     

other attached packages:
[1] stringi_1.1.5     data.table_1.10.4

loaded via a namespace (and not attached):
[1] compiler_3.4.1 tools_3.4.1    yaml_2.1.14 

【问题讨论】:

  • 我也有类似的问题。我认为这与获取文件时如何读取特殊字符有关。我的文本包含“£”,而您的文本包含法语口音“é, è, â, û”。

标签: r stringr stringi


【解决方案1】:

先尝试将文本转换为 ASCII。这将改变字符,并且当您在 R 中获取函数时可能允许相同的行为。

+1 费利佩·阿尔瓦伦加 https://stackoverflow.com/a/45941699/2069472

text <- "Ábcdêãçoàúü"
iconv(text, to = "ASCII//TRANSLIT")

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-24
    • 1970-01-01
    • 2020-01-28
    相关资源
    最近更新 更多