【问题标题】:Find longest word with even number of characters找到偶数个字符的最长单词
【发布时间】:2019-02-13 23:48:08
【问题描述】:

所以我有一个字符串,我需要找到匹配两个约束的单词,即单词中的字符数应该是偶数,并且应该是最长的单词。

例如:

Input: I am a bad coder with good logical skills
Output: skills

刚从 R 开始,所以任何帮助都会很棒。

【问题讨论】:

  • 这个问题涵盖了您的部分帖子:Extract longest word in string,您只需对偶数进行子集化并选择最大的一个。
  • @PoGibas 没错!谢谢..你能告诉我如何计算这个子集吗?
  • 首先,编写一个程序来查找字符串中最长的单词。如果你能做到这一点,那么修改它以忽略具有奇数个字符的单词。

标签: r text-processing


【解决方案1】:

你可以试试图书馆tokenizers

library(tokenizers)

text <- "I am a bad coder with good logical skills"

names(which.max(sapply(Filter(function(x) nchar(x) %% 2 == 0, 
                          unlist(tokenize_words(text))), nchar)))

#[1] "skills" 

【讨论】:

    【解决方案2】:

    这是我的代码:

    input<-"I am a bad coder with good logical skills"
    
    words<-strsplit(input," ")                                      # Split it to words
    
    countWords<-sapply(words,nchar)                                 # Count the length of words
    
    dt<-data.frame( word=unlist(words), length=unlist(countWords) ) # Make a dataframe
    
    dt<-dt[order(dt$length),]                                       # Sort the dataframe based on length
    
    dt<-dt[  which((dt$length %% 2)==1),]                           # Get the words with odd length
    
    dt[nrow(dt),]                                                   # Get the longest word
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-11-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-05-23
      相关资源
      最近更新 更多