[英]Why does my profanity filter not work?
List<String> cursewords = new ArrayList<String>();
cursewords.add("darn it");
cursewords.add("gosh");
cursewords.add("gee whiz");
cursewords.add("golly");
String text = " Golly ";
if (cursewords.contains(text.trim().toLowerCase()) {
System.out.println("found curse:" + text);
}
有一個更好的方法嗎?
我的過濾器未捕獲所需的東西。
當前,您的過濾器僅在text
與cursewords
一項相同(完全沒有其他字符) cursewords
。 要解決此問題,您需要遍歷cursewords
的項目,並檢查text
包含cursewords
。
這是一個簡單的示例(使用增強的for
循環 ):
// Convert the string to lowercase here, instead of within the loop
string lowerCaseText = text.toLowerCase();
for (String curse : cursewords) {
if (lowerCaseText.contains(curse)) {
System.out.println("found curse:" + curse);
}
}
盡管正如其他人所提到的那樣,使用正則表達式來解釋詛咒的變化並避免出現集體錯誤可能會更好。
List.contains()將查找完全匹配。
也許您需要這樣做:
for(String curseword:cursewords) {
//wrong
//if(curseword.contains(text.trim().toLowerCase())) {
if(text.trim().toLowerCase().contains(curseword)) {
...
}
}
您的代碼在此行有一個錯誤:
if (cursewords.contains(text.trim().toLowerCase()) {
附上if
語句用)
,如下所示:
if (cursewords.contains(text.trim().toLowerCase())) {
結果 ,提供的代碼現在可以正常工作:
被發現的詛咒:戈莉
這種方法與正則表達式不同。 它假定您已經將短語解析為單個單詞。
其他人已經指出了您代碼中的錯誤。 但是,一個總體改進是使用詞干分析器對文本進行預處理,然后將輸出結果與更易於管理的“根”詛咒詞集進行比較。 例如,“翻轉”的詞干將是“翻轉”。 然后,而不是每次都針對每個詛咒詞檢查整個文本,而是遍歷文本中的每個預處理詞並檢查其是否等於您所詞干的任何詛咒詞。
其他更明顯的預處理措施是刪除所有標點並使所有文本變為小寫。
Set<String> stemmedCurseWords = new HashSet<String>();
stemmedCurseWords.add("flip");
stemmedCurseWords.add("gosh");
String text = "I was flipping late for work again."
boolean foundCurseWord = false;
String[] stemmedText = preprocess(text);
for (String word : stemmedText) {
if (stemmedCurseWords.contains(word)) {
foundCurseWord = true;
break;
}
}
if (foundCurseWord) {
System.err.println("Bad manners");
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.