[英]Replace multiple consecutive occurrences of a character with a single occurrence
我正在用Java开发自然语言处理应用程序,正在使用IMDB和Amazon的数据。
我遇到了某个数据集,其中包含诸如partyyyyy
类的partyyyyy
。 这些单词对我的分类算法不利。 因此,我想删除它们并添加party
而不是partyyyyyyy
。
我怎样才能做到这一点?
您可以使用regex来查找至少有两次相同字母的字母(因为我们不想删除comma
m
等正确字母)
String data="stoooooop partyyyyyy";
System.out.println(data.replaceAll("([a-zA-Z])\\1{2,}", "$1"));
// | | |
// group 1 match replace with
// from match from group 1
// group 1
// repeated
// twice or more
输出:
stop party
我所知道的英语单词中没有两个以上连续的相同字母。
这种方法无法捕获:
派对的
“弯腰”(加上模棱两可!是“停止”加上一个额外的“ o”还是仅仅是“弯腰”)
尝试使用循环,
String word="Stoooppppd";
StringBuilder res=new StringBuilder();
char first=word.charAt(0);
res.append(first);
for (int i = 1; i < word.length(); i++) {
char ch=word.charAt(i);
if(ch!=first){
res.append(ch);
}
first=ch;
}
System.out.println(res);
您可能希望使用\\ p {L} \\ p {M} *而不是[a-zA-Z]来包含非英语的unicode字母。 因此它将像这样: replaceAll("(\\\\p{L}\\\\p{M}*)(\\\\1{" + maxAllowedRepetition + ",})", "$1");
或以下方式: replaceAll("(\\\\p{L}\\\\p{M}*)\\\\1{" + maxAllowedRepetition + ",}", "$1");
您可以使用此代码段的快速实现。
public static String removeConsecutiveChars(String str) {
if (str == null) {
return null;
}
int strLen = str.length();
if (strLen <= 1) {
return str;
}
char[] strChar = str.toCharArray();
char temp = strChar[0];
StringBuilder stringBuilder = new StringBuilder(strLen);
for (int i = 1; i < strLen; i++) {
char val = strChar[i];
if (val != temp) {
stringBuilder.append(temp);
temp = val;
}
}
stringBuilder.append(temp);
return stringBuilder.toString();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.