【发布时间】:2020-03-13 19:20:38
【问题描述】:
我有一个程序,它从文本文件中获取输入,删除标点符号,然后按单个空格分割并将结果汇总到地图中。我可以让它工作,但我在地图上也得到了一个空的结果,我不知道给出了什么:
扫描仪接受输入:
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);
}
}
如您所见,我首先使用全部替换,然后我想出了我自己的时髦迭代方法(它似乎运行得更快)。在这两种情况下,当我使用 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+") 和 .split(" ") 但我仍然在结果中得到这个空值。
我试图只计算单词和数字的出现次数,为什么我得到这个空值?
更新:在 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] = ' ';
}
【问题讨论】:
-
了解
line中的内容会有所帮助。 -
我会更新问题...
-
了解
line中的内容仍然会有所帮助,而不仅仅是对其中内容的描述。
标签: java regex dictionary split punctuation