我正在用 Java 创建一个贝叶斯过滤系统。目前,我的代码通过使用单独的 .txt
文件来学习垃圾邮件和正常文本; learn.spam("spam.txt");
和 learn.good("good.txt")
。
这两种方法几乎完全相同:
public void good(String file) throws IOException {
A2ZFileReader fr = new A2ZFileReader(file);
String content = fr.getContent();
String[] tokens = content.split(splitregex);
int goodTotal = 0;
for (int i = 0; i < tokens.length; i++) {
String word = tokens[i].toLowerCase();
Matcher m = wordregex.matcher(word);
if (m.matches()) {
goodTotal++;
if (words.containsKey(word)) {
Word w = (Word) words.get(word);
w.countGood();
} else {
Word w = new Word(word);
w.countGood();
words.put(word,w);
}
}
}
public void spam(String file) throws IOException {
A2ZFileReader fr = new A2ZFileReader(file);
String content = fr.getContent();
String[] tokens = content.split(splitregex);
int spamTotal = 0;//tokenizer.countTokens();
for (int i = 0; i < tokens.length; i++) {
String word = tokens[i].toLowerCase();
Matcher m = wordregex.matcher(word);
if (m.matches()) {
spamTotal++;
if (words.containsKey(word)) {
Word w = (Word) words.get(word);
w.countBad();
} else {
Word w = new Word(word);
w.countBad();
words.put(word,w);
}
}
}
Iterator iterator = words.values().iterator();
while (iterator.hasNext()) {
Word word = (Word) iterator.next();
word.calcBadProb(spamTotal);
}
}
现在我试图解决的问题是,我没有两个 .txt
文件,而是使用以下文件:
spam Gamble tonight only for a cheap price of $5 per hand.
ham Sex, I love it. I need it now.
ham yeah I know, I am going tonight that that place, ;) Come join me. You know you want to
ham It is pretty expensive, just this and that for only ($900)
spam Call 123123123 to use for free porn
每行只有一条消息,垃圾消息以 spam 开头,好消息以 ham 开头,带有一个选项卡。
如何更改方法,以便仅使用一种方法和一个 .txt
文件来训练它。
最佳答案
将 good
方法更改为:
public void good(String content) {
String[] tokens = content.split(splitregex);
int goodTotal = 0;
for (int i = 0; i < tokens.length; i++) {
String word = tokens[i].toLowerCase();
Matcher m = wordregex.matcher(word);
if (m.matches()) {
goodTotal++;
if (words.containsKey(word)) {
Word w = (Word) words.get(word);
w.countGood();
} else {
Word w = new Word(word);
w.countGood();
words.put(word,w);
}
}
}
}
对垃圾邮件
执行几乎完全相同的操作。
然后编写一个方法train
来读取文件,将其分割成行,然后根据每行中的第一个单词调用正确的方法。
之后,将所有内容合并到一个方法中就很简单了。
关于java - 将读取两个文件的两种方法合并为用一种方法读取一个文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22078074/