java - 如何使用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;
}
提前致谢。
解决方案
一种方法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
推荐阅读
- python - Tornado 无效的 x-www-form-urlencoded 正文:“latin-1”编解码器无法编码位置 774-777 中的字符:序数不在范围内(256)
- javascript - NodeJS:如何断言是否使用 sinon 调用了事件回调函数
- protractor - 如何在量角器中选择日期选择器的日期
- javascript - 有没有办法将父 css 泄漏到 Vue 中的子组件?
- asp.net-core - TestHost 生成无效的 URI:无法确定 URI 的格式
- elasticsearch - 为什么文件没有被删除?deleteByQuery 成功但不删除任何内容
- gradle - java.lang.NoSuchFieldError: gradle artifactoryPublish 任务期间的 INSTANCE 错误
- javascript - “addEventListener”在幕后是如何工作的?
- drupal - Drupal 7:如何发送 HTML 电子邮件
- android-studio - 为什么我的 Android Layout Design 在我的智能手机上无法正常工作