繁体   English   中英

读取.txt文件以查看是否在其他.txt文件中找到了单词?

[英]Reading a .txt file to see if a word is found in a different .txt file?

我迷路了,需要指导。 我写了代码来扫描book.txt,但是如何比较input.txt和book.txt中的单词呢?

我认为这会工作

Scanner scan = new Scanner("book.txt");

Set<String> list = new HashSet<String>();
String word = "";

while(scan.hasNextLine())
    list.add(scan.nextLine());
scan.close();
scan = new Scanner("input.txt");
while(scan.hasNextLine())
    if(!list.contains((word = scan.nextLine()))) //word from input.txt is not in book.txt
        System.out.println(word); //print the word to the console

scan.close();

如果不能使用HashSet,则创建自己的hashFunction

最常用的hashFunction是这样的:

public static int mod = 1000007;
private static Long hashFunction(String word) {
        long hash = 5831;
        for (int i = 0; i < word.length(); ++i) {
            hash *= 33;
            hash %= mod;
            hash += word.charAt(i);
            hash %= mod;
        }
        return hash;
    }

hashFunction的基本思想是根据单词创建一个哈希,然后用一个布尔值true表示该数组的存在来填充该数组。

当您创建具有所有哈希值设置的整个hashTable时。 然后只需为目标单词创建一个哈希值,然后检查哈希表中是否存在该哈希值即可。

暂无
暂无

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

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