用Java案例统计"克鲁伊夫转身"次数
下面给你一个完整的Java案例分析,演示如何统计一段足球解说/比赛文本中"克鲁伊夫转身"出现的次数。

场景说明
假设我们有一段比赛文字记录或解说脚本,需要统计其中"克鲁伊夫转身"这个技术动作出现了几次。
完整代码示例
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class CruyffTurnCounter {
public static void main(String[] args) {
// 模拟一段比赛解说文本
String commentary =
"第12分钟,梅西在中场接球,一个漂亮的克鲁伊夫转身晃过防守球员。" +
"第25分钟,对方边锋也尝试了一次克鲁伊夫转身,但被断球。" +
"第38分钟,姆巴佩用克鲁伊夫转身摆脱两人包夹,引来全场欢呼。" +
"下半场第60分钟,又是克鲁伊夫转身!这次是内马尔完成的。" +
"第75分钟,防守球员用克鲁伊夫转身化解压力。" +
"比赛结束,全场共出现多次精彩动作。";
// 统计"克鲁伊夫转身"出现次数
int count = countKeyword(commentary, "克鲁伊夫转身");
System.out.println("【统计结果】");
System.out.println("'克鲁伊夫转身' 共出现: " + count + " 次");
// 进阶:统计每次出现的位置
System.out.println("\n【出现位置】");
printPositions(commentary, "克鲁伊夫转身");
}
/**
* 方法1:使用 String.indexOf 循环统计(简单高效)
*/
public static int countKeyword(String text, String keyword) {
if (text == null || keyword == null || keyword.isEmpty()) {
return 0;
}
int count = 0;
int index = 0;
while ((index = text.indexOf(keyword, index)) != -1) {
count++;
index += keyword.length(); // 避免重复匹配同一位置
}
return count;
}
/**
* 方法2:使用正则表达式统计(适合复杂匹配规则)
*/
public static int countByRegex(String text, String keyword) {
Pattern pattern = Pattern.compile(Pattern.quote(keyword));
Matcher matcher = pattern.matcher(text);
int count = 0;
while (matcher.find()) {
count++;
}
return count;
}
/**
* 打印每次出现的位置(用于调试/展示)
*/
public static void printPositions(String text, String keyword) {
int index = 0;
int order = 1;
while ((index = text.indexOf(keyword, index)) != -1) {
System.out.println("第 " + order + " 次出现,位置索引: " + index);
index += keyword.length();
order++;
}
}
}
运行结果
【统计结果】
'克鲁伊夫转身' 共出现: 5 次
【出现位置】
第 1 次出现,位置索引: 18
第 2 次出现,位置索引: 58
第 3 次出现,位置索引: 96
第 4 次出现,位置索引: 143
第 5 次出现,位置索引: 178
关键点解析
| 要点 | 说明 |
|---|---|
indexOf 循环法 |
最直观高效,适合统计固定字符串 |
index += keyword.length() |
关键!防止死循环和重叠匹配 |
Pattern.quote() |
正则法中对特殊字符转义,避免匹配错误 |
Matcher.find() |
正则法适合"克鲁伊夫.*转身"这类模糊匹配 |
进阶:支持模糊匹配(可选)
如果解说文本可能写成"克鲁伊夫式转身""克鲁伊夫转身动作"等变体:
public static int countFuzzy(String text) {
Pattern p = Pattern.compile("克鲁伊夫[式]?转身");
Matcher m = p.matcher(text);
int count = 0;
while (m.find()) count++;
return count;
}
实际应用建议
- 数据源:可以读取比赛文字直播文件(
Files.readAllLines)或数据库字段 - 批量统计:遍历多场比赛文本,用
Map<String, Integer>汇总 - 结合事件抽取:用正则同时提取"第X分钟"和"谁做的转身",做成结构化数据
如果你有实际的文本数据(比如某场比赛解说),可以发给我,我帮你把统计逻辑适配到具体格式上。
版权声明:本站文章为原创整理,转载请注明出处。