繁体   English   中英

比较两个文本文件,看看第二个文件中的单词在第一个文件中出现了多少次

[英]Compare two text files and see how many times the words in the 2nd file occurs in the 1st file

我试图找出 text2.txt 中的单词出现在 text1.txt 中的次数。 当我运行我的代码时,它只打印出 text2.txt 单词出现在 text1.txt 0 次。

一些 text1.txt 看起来像这样:

2 A well-made but emotionally scattered film whose hero gives his heart only to the dog .     
2 Those who love Cinema Paradiso will find the new scenes interesting , but few will find the movie improved .

一些 text2.txt 看起来像这样:

will
dog
the
movie
find

这是我的代码:

try {    
File file1 = new File("text1.txt");
File file2 = new File("text2.txt");
Scanner scan1 = new Scanner(file1);
Scanner scan2 = new Scanner(file2);
String text1;
String text2;
int wordCount = 0;
while(scan1.hasNext() && scan2.hasNext()) {
    text1 = scan1.nextLine();
    text2 = scan2.nextLine();
    if(text1.contains(text2)) {
        wordCount++;

    }
    System.out.println(file2 + " appears in " + file1 + " " + wordCount +" times");

}
} catch(Exception e) {
        System.out.println("Error! \n" + e + "\n");
    }
}

nextLine() 返回一个直到换行符的字符串。

你的 text1 有两行,你的 text2 文件有更多。 至于现在您只是比较文件的第一行是否包含第二个文件的第一个单词。 然后检查第一个文件的第二行是否包含第二个文件的第二个单词。

您应该遍历第一个文件的每个单词,并与第二个文件的每个单词一个一个进行比较。 您可以通过将文件中的单词转换为两个数组,然后使用两个 for 循环来实现这一点。

如果字符串至少出现一次,compare() 也会返回 true,因此如果单词在字符串中出现两次,您将不会知道。

如果text2.txt是字典,则需要text2.txt其读入一组单词。

然后,在读取text1.txt的内容时,需要将每一行拆分成单词,然后检查某个单词是否在字典中,如果是,则计算其出现次数,因此结果应该是频率图。

使用 Stream API,实现可能如下所示:

Set<String> dictionary = Files
    .lines(Paths.get("text2.txt")) // Stream<String>
    .collect(Collectors.toSet()); // assuming each line is a separate word

Map<String, Long> freqMap = Files
    .lines(Paths.get("text1.txt")) // Stream<String> multi-word lines
    .flatMap(s -> Arrays.stream(s.split("\\s+"))) // Stream<String> words separated with one or more whitespaces
    .filter(dictionary::contains) // Stream<String> - keep only dictionary words
    .map(Collectors.groupingBy(
        w -> w, // or Function.identity()
        Collectors.counting() // count frequency as long
    ));

// output the map sorted by descending frequency and words
freqMap.entrySet()
    .stream()
    .sorted(Map.Entry.<String, Long>comparingByValue().reversed()
        .thenComparing(Map.Entry.comparingByKey())
    ) // Stream<Map.Entry<String, Long>>
    .forEach(e -> System.out.println(e.getKey() + ": " + e.getValue()));

根据区分大小写的要求,可能需要将字典中的单词转换为单个大小写(小写或大写)并使用相同的大小写:

Set<String> dictionary = Files
    .lines(Paths.get("text2.txt")) // Stream<String>
    .map(String::toLowerCase)
    .collect(Collectors.toSet()); // assuming each line is a separate word

// in freqMap..
// ...
    .filter(word -> dictionary.contains(word.toLowerCase())) // Stream<String>
// ...

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM