Java:计算单词的出现次数,程序计数'empty'单词



我有一个程序,它从文本文件中获取输入,删除标点符号,然后按单个空格进行拆分,并将结果统计到地图中。我可以让它工作,但我在地图上也得到了一个空结果,我不知道是什么给出的:

扫描仪接收输入:

try
{
Scanner input = new Scanner(file);
String nextLine;
while (input.hasNextLine())
{
nextLine = input.nextLine().trim();
processLine(nextLine, occurrenceMap);
}
input.close();
}
catch(Exception e) { System.out.println("Something has gone wrong!");}

它所提取的文本文件是詹姆斯国王版本的圣经然后一个单独的函数处理每一行:

//String[] words = line.replaceAll("[^a-zA-Z0-9 ]", " ").toLowerCase().split("\s+"); // runtime for  bible.txt is ~1600ms
// changed to simple iteration and the program ran MUCH faster:
char[] letters = line.trim().toCharArray();
for (int i=0; i<letters.length; i++)
{
if (Character.isLetterOrDigit(letters[i])) {continue;}
else {letters[i] = ' ';}
}
String punctuationFree = new String(letters);
String[] words = punctuationFree.toLowerCase().split("\W+");
// add each word to the frequency map:
for (int i=0; i<words.length; i++)
{
if (! map.containsKey(words[i]))
{
map.put(words[i], 1);
}
else
{
int value = (int)map.get(words[i]);
map.put(words[i], ++value);
}
}

正如你所看到的,我首先用了一个replace-all,然后我提出了我自己的时髦迭代方法(它似乎运行得更快(。在这两种情况下,当我使用PrintWriter打印结果时,我在开始时都会得到一个奇怪的条目:

num occurences/ (number /word)
25307 :     // what is up with this empty value ?
1 : 000     // the results continue in sorted order
2830 : 1
2122 : 10
6 : 100
9 : 101
29 : 102
23 : 103
36 : 104
46 : 105
49 : 106

我已尝试将String[] words = punctuationFree.toLowerCase().split("\W+");更改为.split("\s+"(和.splite("(,但结果中仍然存在此空值。

我试图只计算单词和数字的出现次数,为什么我得到这个空值?

更新:有人建议Character.isLetterOrDigit((可能会返回不需要的字符,我重写了检查,以便只获得我想要的字符。尽管如此,我仍然得到一个神秘的空值:

for (int i=0; i<letters.length; i++)
{
if ((letters[i] >= 'a' && letters[i] <= 'z') || 
(letters[i] >= 'A' && letters[i] <= 'Z'))
{continue;}
else if (letters[i] >= '0' && letters[i] <= '9')
{continue;}
else if ((letters[i] == ' ')||(letters[i] =='n')||(letters[i] == 't'))
{continue;}
else
letters[i] = ' ';
}

只是猜测,但Character方法IsLetterOrDigit被定义为适用于整个unicode范围。根据文档页面,它包括所有"有效字母和十进制数字是UnicodeCategory中以下类别的成员:大写字母、小写字母、标题字母、修饰符字母、其他字母或DecimalDigitNumber。">

我认为这种方法保留了你不想要的字符(特别是ModifierLetter和/或OtherLetter(,这些字符没有包含在你的字体中,所以你看不到它们。

编辑1:我测试了你的算法。事实证明,一个空行绕过了测试,因为它跳过了for循环。你需要在刚从文件行读取一行后添加一行长度,这是:

if (nextLine.length() == 0) {continue;}

编辑2:此外,由于您正在扫描每个字符以剔除"非单词和非数字",因此您还可以结合逻辑来创建单词并将其添加到集合中。可能是这样的:

private static void WordSplitTest(String line) {
char[] letters = line.trim().toCharArray();
boolean gotWord = false;
String word = "";
for (int i = 0; i < letters.length; i++) {
if (!Character.isLetterOrDigit(letters[i])) {
if(!gotWord) {continue;}
gotWord = false;
AddWord(word);
}
if (gotWord) {
word += Character.toString(letters[i]);
}
}
}
private static void AddWord(String word) {
if (!map.containsKey(word)) {
map.put(word, 1);
} else {
int value = (int) map.get(word);
map.put(word, ++value);
}
}

相关内容

最新更新