【问题标题】:Finding and converting all numbers into their corresponding names in R在 R 中查找所有数字并将其转换为相应的名称
【发布时间】:2020-03-25 14:29:20
【问题描述】:

我有一个单列数据框,其中每一行都是一个语句。这些语句大多是字母字符,但也有一些数字字符。我正在尝试找到所有数字字符并将它们替换为相应的字母字符。

基本上,我想从这里开始

 "I looked at the watermelons around 12 today"
 "There is a dog on the bench"
 "the year is 2017"
 "I am not hungry"
 "He turned 1 today"

进入(或类似的东西)

 "I looked at the watermelons around twelve today"
 "There is a dog on the bench"
 "the year is two thousand seventeen"
 "I am not hungry"
 "He turned one today"

有一些我熟悉的函数可以将数字转换为单词,例如 xfun 包中的 numbers_to_words 函数,但我不知道如何系统地为整个数据框执行此操作。

【问题讨论】:

标签: r string int alphanumeric


【解决方案1】:

这是stringrenglish 包的一种方法。

library(stringr)
library(english)
data<-  c("I looked at the watermelons around 12 today", "There is a dog on the bench", "the year is 2017", "I am not hungry", "He turned 1 today")
Replacement <-  lapply(str_extract_all(data,"[0-9]+"),function(x){
                   as.character(as.english(as.numeric(x)))})

sapply(seq_along(data),
       function(i){
         ifelse(grepl('[0-9]+',data[i]),
                str_replace_all(data[i],"[0-9]+",Replacement[[i]]),
                data[i])})
[1] "I looked at the watermelons around twelve today" "There is a dog on the bench"                    
[3] "the year is two thousand seventeen"              "I am not hungry"                                
[5] "He turned one today"  

【讨论】:

  • 这似乎不适用于我的机器。我仍然得到数值为数字。您的数据是什么数据类型?我的作为 chr 出现。
【解决方案2】:

实际上我不知道一个简单的功能或类似的东西,但我有一个可能有点糟糕的解决方案给你:

library(xfun)
a <- "I looked at the watermelons around 12 today"        
y <- numeric(nchar(a))        
for(i in 1:nchar(a))        
{        
  y[i]<-as.numeric(substr(a,i,i))        
}        
x <- n2w(as.numeric(paste(na.omit(y), collapse="")))        
z <- which(y != "NA")        
paste(c(substr(a, 1, z[1]-1), x, substr(a, z[length(z)] + 1, nchar(a))), collapse = "")

目前它只适用于一句话中的一个数字

【讨论】:

  • 有没有办法在 Python 中做到这一点?
  • 不幸的是我对python不太熟悉
  • 有包“tidyr”和函数“extract_numeric”,所以你可以使用“extract_numeric(yoursentence)”来查找数字或者替代方法是as.numeric(gsub("[^\ \d]+", "", 你的句子, perl=TRUE))
  • @Triss 仅供参考,对于代码格式化,在代码块之前使用 3 个反引号,在代码块之后使用 3 个反引号,您不需要在每一行都使用反引号。
猜你喜欢
  • 2012-01-01
  • 1970-01-01
  • 2018-03-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-02-02
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多