![](/img/trans.png)
[英]How to count the number of unique words in a text file? Not allowed to use Hash
[英]How to count unique words in a text file?
我已经实现了用于计数以下内容的代码:-字符-单词-行-文本文件中的字节。 但是如何计算字典大小:此文件中使用的不同单词数? 另外,如何实现只能对字母进行迭代的迭代器? (忽略空格)
public class wc {
public static void main(String[] args) throws IOException {
//counters
int charsCount = 0;
int wordsCount = 0;
int linesCount = 0;
Scanner in = null;
File file = new File("Sample.txt");
try(Scanner scanner = new Scanner(new BufferedReader(new FileReader(file)))){
while (scanner.hasNextLine()) {
String tmpStr = scanner.nextLine();
if (!tmpStr.equalsIgnoreCase("")) {
String replaceAll = tmpStr.replaceAll("\\s+", "");
charsCount += replaceAll.length();
wordsCount += tmpStr.split("\\s+").length;
}
++linesCount;
}
System.out.println("# of chars: " + charsCount);
System.out.println("# of words: " + wordsCount);
System.out.println("# of lines: " + linesCount);
System.out.println("# of bytes: " + file.length());
}
}
}
要获得独特的单词及其数量:
1.将获得的行从文件拆分为字符串数组
2.将此字符串数组的内容存储在哈希集中
3.重复步骤1和2,直到文件结束
4.从哈希集中获取唯一单词及其数量
我更喜欢发布逻辑和伪代码,因为它将帮助OP通过解决发布的问题来学习一些知识。
嘿@JeyKey可以使用HashMap。 在这里我也使用Iterator。 您可以签出此代码。
public class CountUniqueWords {
public static void main(String args[]) throws FileNotFoundException {
File f = new File("File Name");
ArrayList arr=new ArrayList();
HashMap<String, Integer> listOfWords = new HashMap<String, Integer>();
Scanner in = new Scanner(f);
int i=0;
while(in.hasNext())
{
String s=in.next();
//System.out.println(s);
arr.add(s);
}
Iterator itr=arr.iterator();
while(itr.hasNext())
{i++;
listOfWords.put((String) itr.next(), i);
//System.out.println(listOfWords); //for Printing the words
}
Set<Object> uniqueValues = new HashSet<Object>(listOfWords.values());
System.out.println("The number of unique words: "+uniqueValues.size());
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.