我想知道(有例子!)是否有办法搜索列表(不是文件),如果找到它替换它



我想知道(有例子!)是否有办法搜索列表(不是文件),如果找到它,请替换它。

背景:制作服务器,但我希望它审查脏话,而我拥有的系统效率不够高。

当前代码:

     String impmessage = message.replaceAll("swearword1", "f***");
     String impmessage2 = impmessage.replaceAll("swearword2", "bi***");
     String impmessage3 = impmessage2.replaceAll("swearword3", "b***");
     String impmessage4 = impmessage3.replaceAll("swearword4", "w***");
     ...
     String impmessage8 = impmessage7.replace('%', '&');

整个沙邦。但是当我想在过滤器中添加一个新单词时,我必须在那里添加另一个单词。

您的基本解决方案如下:

Map<String, String> mapping = new HashMap();
mapping.put("frak","f***");
String censoredMsg = message;
for (String word : mapping.KeySet()) {
  censoredMsg = censoredMsg.replaceAll(word, mapping.get(word));
}

如何创建映射在某种程度上取决于您。这是另一个更全面的解决方案,包括从随机文件中提取:

public class TheMan {
  private Set<String> uglyWords;
  public TheMan() {
    getBlacklist();
  }
  private void getBlacklist() {
    Scanner scanner = new Scanner(new File("wordsidontlike.txt"));
    while (scanner.hasNext()) {
      String word = scanner.nextLine();
      uglyWords.add(word);
    }
  }
  public String censorMessage(String message) {
    String censoredMsg = message;
    for (String word : uglyWords) {
      String replacement = word.charAt(0);
      StringUtils.rightPad(replacement, word.length(), '*');
      censoredMsg = censoredMsg.replaceAll(word, replacement);
    }
    return censoredMsg;
  }
}

相关内容

最新更新