首页 > 解决方案 > 如何使用Java或R计算字符串中不同子字符串(数学符号)的频繁出现

问题描述

我有以下字符串(有时子字符串之间没有空格):

str = "<= < / + * + cos sin (service <= service)+ * hello)rate"

子字符串已经预定义为:

mathsubstring = {<=, <, / , +, cos, sin }

并且正常的子字符串也是预定义的:

substring[]= {"service","hi","rate","world"};

我想计算每个特定子字符串的频繁出现,例如:

The output will be :
<= = 2
<  = 1
/ = 1
+ = 3
* = 2
cos = 1
sin = 1

到目前为止,我设法从字符串中找到子字符串,请参阅以下 java 代码:

String substring[]= {"service","hi","rate","world"};

        int count=0;
        for (int j=0; j< substring.length; j++)
        {
            count=0;
            Pattern p = Pattern.compile("\\b"+substring[j]+"\\b");
            Matcher m = p.matcher(str);
            while(m.find()) {
            count++;
            }
            Countsubstring = Countsubstring + count;
        }

提前致谢。

标签: javar

解决方案


一种方法R,在每个处拆分字符串,space然后计算不同元素的出现次数:

编辑
使用第三个字符串和新约束,考虑元素可以用空格或左括号或右括号分隔:

str <- "<= < / + * + cos sin (service <= service)+ * hello)rate"
mathsubstring <- c("<=", "<", "/", "+", "cos", "sin")

t_elt <- table(strsplit(str, " |\\(|\\)"))
t_elt[mathsubstring]
<=   <   /   + cos sin 
 2   1   1   3   1   1

如果您想知道数学子字符串的总出现次数:

sum(t_elt[mathsubstring])
#[1] 9

以前的代码与以前的str

table(strsplit(str, " "))

       *       /       +       <      <=     cos service     sin 
      2       1       3       1       2       1       2       1 

service如果您愿意,您可以在之后删除(或其他非数学符号),例如:

tab <- table(strsplit(str, " "))
mathsubstring <- c('<=', '<', '/', '+', 'cos', 'sin')
tab[names(tab) %in% mathsubstring]

用你的第二个字符串:

str = "<= < / + * + cos sin service <= service + * hello rate"
table(strsplit(str, " "))

      *       /       +       <      <=     cos   hello    rate service     sin 
      2       1       3       1       2       1       1       1       2       1


推荐阅读