【问题标题】:Parse a character string and later re-assemble it解析一个字符串,然后重新组装它
【发布时间】:2013-07-18 17:56:05
【问题描述】:

我正在尝试将字符串解析为其部分,检查每个部分是否存在于单独的词汇表中,然后仅重新组合那些部分在词汇表中的字符串。词汇表是单词的向量,与我要比较的字符串分开创建。最终目标是创建一个数据框,其中仅包含单词部分在词汇表中的字符串。

我已经编写了一段代码来将数据解析为字符串,但不知道如何进行比较。如果您认为解析数据不是最佳解决方案,请告诉我。

这是一个例子: 假设我有三个字符串:

"The elephant in the room is blue",
"The dog cannot swim",
"The cat is blue"

我的词汇由以下单词组成:

cat,    **the**,    **elephant**,    hippo,
**in**,    run,    **is**,    bike,
walk,    **room, is, blue, cannot**

在这种情况下,我将只选择第一个和第三个字符串,因为它们的每个单词部分都与我的词汇表中的一个单词匹配。我不会选择第二个字符串,因为“狗”和“游泳”这两个词不在词汇表中。

谢谢!

根据请求,附上我迄今为止编写的用于清理字符串并将它们解析为唯一单词的代码:

animals <- c("The elephant in the room is blue", "The dog cannot swim", "The cat is blue")

animals2 <- toupper(animals)
animals2 <- gsub("[[:punct:]]", " ", animals2)
animals2 <- gsub("(^ +)|( +$)|(  +)", " ", animals2)

## Parse the characters and select unique words only
animals2 <- unlist(strsplit(animals2," "))
animals2 <- unique(animals2)

【问题讨论】:

  • 你能分享你到目前为止所做的事情吗?这听起来像是strsplit%in%paste 的简单案例...但是如果没有您的初始处理代码,很难说该怎么做!
  • 逻辑不通你的词汇是什么词? the 这个词是粗体/加星标的,它出现在第二个字符串中。
  • 那些* 字符看起来应该是正则表达式。 **the** 是否意味着the 可以出现在字符串的任何位置,而**room 意味着room 只能出现在字符串的末尾?

标签: r parsing pattern-matching


【解决方案1】:

我会怎么做:

  1. 读取数据
  2. 清理词汇以删除多余的空格和 *
  3. 遍历字符串,使用setdiff

我的代码是:

## read your data
tt <- c("The elephant in the room is blue",
"The dog cannot swim",
"The cat is blue")
vocab <- scan(textConnection('cat,    **the**,    **elephant**,    hippo,
**in**,    run,    **is**,    bike,
walk,    **room, is, blue, cannot**'),sep=',',what='char')
## polish vocab
vocab <- gsub('\\s+|[*]+','',vocab)
vocab <- vocab[nchar(vocab) >0]
##
 sapply(tt,function(x){
+     x.words <- tolower(unlist(strsplit(x,' '))) ## take lower (the==The)
+     length(setdiff(x.words ,vocab)) ==0
+ })
The elephant in the room is blue              The dog cannot swim                  The cat is blue 
                            TRUE                            FALSE                             TRUE 

【讨论】:

  • 像魅力一样工作!谢谢。我在 lapply() 周围添加了 melt() 以将列表转换为变量,因为最后需要一个数据框。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-03-18
  • 1970-01-01
  • 2012-07-10
相关资源
最近更新 更多