java 敏感词汇分析程序
时间: 2024-03-20 11:45:33 浏览: 35
可以使用 Trie 树(字典树)实现敏感词汇的分析程序。以下是一个简单的 Java 实现:
```java
public class SensitiveWordsAnalyzer {
private TrieNode root;
public SensitiveWordsAnalyzer() {
root = new TrieNode();
}
public void addSensitiveWord(String word) {
TrieNode node = root;
for (char c : word.toCharArray()) {
if (!node.containsKey(c)) {
node.put(c, new TrieNode());
}
node = node.get(c);
}
node.setEnd();
}
public boolean containsSensitiveWords(String text) {
TrieNode node = root;
for (int i = 0; i < text.length(); i++) {
char c = text.charAt(i);
if (node.containsKey(c)) {
node = node.get(c);
if (node.isEnd()) {
return true;
}
} else {
node = root;
}
}
return false;
}
private static class TrieNode {
private TrieNode[] children;
private boolean isEnd;
public TrieNode() {
children = new TrieNode[256];
}
public boolean containsKey(char c) {
return children[c] != null;
}
public TrieNode get(char c) {
return children[c];
}
public void put(char c, TrieNode node) {
children[c] = node;
}
public boolean isEnd() {
return isEnd;
}
public void setEnd() {
isEnd = true;
}
}
}
```
使用示例:
```java
SensitiveWordsAnalyzer analyzer = new SensitiveWordsAnalyzer();
analyzer.addSensitiveWord("敏感词汇1");
analyzer.addSensitiveWord("敏感词汇2");
String text = "这是一段包含敏感词汇1和敏感词汇2的文本";
if (analyzer.containsSensitiveWords(text)) {
System.out.println("文本中包含敏感词汇");
} else {
System.out.println("文本中不包含敏感词汇");
}
```
输出结果为:
```
文本中包含敏感词汇
```
阅读全文