首页 > 解决方案 > 将单词分解成字母模式:代码未按预期工作

问题描述

我有一个单词列表和单词中常见字符模式的列表。该脚本通过运行单词列表来工作,然后检查在单词中找到了哪些字符模式,最后在表格中显示结果。

完成的表格应如下所示:

word    CharPatLen  charpat01 charpat02 charpat03 charpat04
father  4           f         a         th        er
there   3           th        er        e
after   4           a         f         r         er

相反,我得到了下表,并且在字段 charpat03 上“那里”一词开始出现问题。这里的 'f' 应该代替 'e' 并且下一行是空白的。

word    CharPatLen  charpat01 charpat02 charpat03 charpat04
father  4           f         a         th        er
there   3           th        er        f
after   4  

我还收到以下警告消息,我试图通过谷歌搜索修复但没有成功

'Warning message:
In as.numeric(paste(as.numeric(charIndexStart), charIndexEnd, sep = "")) :
  NAs introduced by coercion'

帮助!我不确定脚本出了什么问题。

谢谢,花时间看我的帖子。

##################################################
# This script loops through a word list then break the word into character (char)
# pattern found character pattern list 
# 
# e.g 
#using the word list         ( father, there, after)
#using the char pattern list (th,er,f, a, e,t)
# 
# it should return the following
# 
# word    CharPatLen  charpat01 charpat02 charpat03 charpat04
# father  4           f         a         th        er
# there   3           th        er        e
# after   4           a         f         r         er
#####################################################


word      <- c("father", "there", "after")
CharPatLen <- c(0, 0, 0)
charpat01 <- c("", "", "" )
charpat02 <- c("", "", "" )
charpat03 <- c("", "", "" )
charpat04 <- c("", "", "" )
charpat05 <- c("", "", "" )
wordList <- data.frame(word, CharPatLen, charpat01,charpat02,charpat03,charpat04,charpat05,stringsAsFactors = F)

textPat <- c("th", "er", "f","a","e","t")
frequency <- c(0,0,0,0,0,0)
textPattern <- data.frame(textPat,frequency, stringsAsFactors = F)


#######################################
# 01 loop through word list              
#######################################
for (text in wordList$word) {#4loop01
  # track what parts of the word a found char pattern
  charSelectionTracker <- rep(1, times=nchar(text))

  #found char patterns from word, order/range and the char pattern
  FoundcharPatternholder  <- data.frame(order= integer(),charPattern = character())

  #########################################
  # 02 loop through character patterns list  
  #########################################
     for (pattern in textPattern$textPat) { #4loop02


       if(sum(charSelectionTracker)== 0)
       {#charSelect

         #reorder patterns
         rank <- order(FoundcharPatternholder$order)
         FoundcharPatternholder<- FoundcharPatternholder[rank,]

         wordList[which(wordList$word == text),"CharPatLen"] = nrow(FoundcharPatternholder)

         for (patPao in 1:nrow(FoundcharPatternholder))
          {
           wordList[which(wordList$word == text),patPao+2] = as.character(FoundcharPatternholder[patPao,2])
           }

         break
       }#charSelect 

        #find all char pattern in word
        patFoundAt <- unlist(gregexpr (pattern,text)[[1]])

        #########################################
        # 03 check that each pattern within a word is valid and not used in an other char pattern
        #########################################
         for (charIndexStart in patFoundAt) 
               {#4loop03


           charIndexEnd = charIndexStart + nchar(pattern)-1

           if( sum(charSelectionTracker[charIndexStart:charIndexEnd]) == nchar(pattern) & sum(charSelectionTracker)> 0)
               {#PatExtract

             #track what letters have been used by character pattern
             charSelectionTracker[charIndexStart:charIndexEnd]=0

             #order/index in pattern 
             patIndex <- as.numeric(paste(as.numeric(charIndexStart),charIndexEnd,  sep = ''))

             innerPatternholder  <- data.frame(order= patIndex,charPattern = pattern)

             FoundcharPatternholder <- rbind(FoundcharPatternholder, innerPatternholder)
              }#PatExtract

            }#4loop03



     } #4loop02

  }#4loop01

标签: r

解决方案


最好不要丢失嵌套的 for 循环。str_extract_all并且str_count来自 stringr 包可能有助于简化代码:

library(stringr)

## data
words <- c("father", "there", "after")
textPat <- paste(c("th", "er", "f","a","e","t"), collapse = "|")

## extract matching patterns 
charPat <- str_extract_all(words, textPat, simplify = TRUE) 
colnames(charPat) <- sprintf("charpat%02d", seq_len(ncol(charPat)))

## count matched patterns per word 
charPatLen <- str_count(words, textPat)

## combine into data.frame
cbind(data.frame(word = words, CharPatLen = charPatLen), charPat)
#>     word CharPatLen charpat01 charpat02 charpat03 charpat04
#> 1 father          4         f         a        th        er
#> 2  there          3        th        er         e          
#> 3  after          4         a         f         t        er

reprex 包(v0.3.0)于 2019 年 7 月 5 日创建


推荐阅读