简体   繁体   中英

How do I load text from a text file and compare against another text file?

I've written a small program that reads text from a file and prints the reverse of every word within the text file.

Now I want to try and efficiently find if all the words that are reverse are actual words in the english dictionary and prints these out as a list sorted by string length with each pair occurring once.

Here's what I've been able to write so far

    String word;
    String[] reverse;
    int wordLength;

/**
 * @param args the command line arguments
 */
public static void main(String[] args) throws FileNotFoundException {
    // TODO code application logic here

    Map<Integer, String> aMap2 = new HashMap<Integer, String>();
    String mString = "";
    int mInt = 0;
    String word;
    String[] reverse = new String[1];
    int wordLength;

    FileInputStream fileIn = new FileInputStream ("example.txt”);
    //text in the text file - "what he saw was not part of a trap just a ton of crazy snow"
    Scanner scan = new Scanner(fileIn);
    Scanner lineScanner;
    Scanner wordscanner = null;
    String aLine;
    String aWord;

    while(scan.hasNextLine()){
        aLine = scan.nextLine();
        lineScanner = new Scanner(aLine);
        lineScanner.useDelimiter(",");
        word = lineScanner.next();
        System.out.println(word);
        try{
            wordscanner = new Scanner(new File("example.txt"));
        } catch(FileNotFoundException x){
            x.printStackTrace();
        }

        while(wordscanner.hasNext()){
            Scanner newWord = new Scanner(wordscanner.next());
            boolean b;
            while(b = newWord.hasNext()){
                String foundWord = newWord.next();
                wordLength = foundWord.length();
                char ch = ' ';
                String reverseWord = “";

                for(int i = wordLength-1; i >= 0; i--){
                    ch = foundWord.charAt(i);
                    //System.out.println(ch);
                    reverseWord = reverseWord + ch;
                }

                for(int k = 0; k < reverse.length; k++){
                      reverse[k] = foundWord + ", " + reverseWord;
                      mString = reverse[k];
                      mInt = reverse[k].length();
                      aMap2.put(mInt, mString);
                }
            }
        }
    }
    Map<Integer, String> sorted = sortByKeys(aMap2);
    System.out.println(sorted);
}


public static <K extends Comparable,V extends Comparable> Map<K,V> sortByKeys(Map<K,V> map){
    List<K> keys = new LinkedList<K>(map.keySet());
    Collections.sort(keys);

    //LinkedHashMap will keep the keys in the order they are inserted
    //which is currently sorted on natural ordering
    Map<K,V> sortedMap = new LinkedHashMap<K,V>();
    for(K key: keys){
        sortedMap.put(key, map.get(key));
    }

    return sortedMap;

    // http://javarevisited.blogspot.co.uk/2012/12/how-to-sort-hashmap-java-by-key-and-value.html
}

This gives me the following result

what he saw was not part of a trap just a ton of crazy snow

{4=a, a, 6=of, fo, 8=ton, not, 10=snow, wons, 12=crazy, yzarc}

Now, my problem is how do I cross check the reverse of the words (preferably character by character) with a dictionary text file to see if the reverse words make up meaningful words?

I've looked around here and I've seen some suggestions but I couldn't find one that helped me understand how to solve my current issue.

I've thought of using a Binary Search Tree, my idea was to load the dictionary file into a Binary Tree and search the Tree to see if the reverse words make up existing words then print them out. But I've been unable to proceed due to the fact that I don't understand how to get a string from one text file then compare it with a second text file.

Lastly, can you help point me in the right direction in getting the words to appear in a 2D Array, please?! I tried it a few times but it just doesn't work and I'm out of ideas :( !

THanks in advance.

You can read the dictionary file line by line. assuming that each line contains a single word you need to put that line into a hashset. Then you can go over the words that you read from the first file, reverse each of them and check that the reversed word is in that hash set.

public Set<String> readFileIntoSet(String fileName) {
  Set<String> result = new HashSet<String>();
  for (Scanner sc = new Scanner(new File(fileName)); sc.hasNext(); ) 
    result.add(sc.nextLine());
  return result;
}

In your main method add a call to readFileIntoSet :

Set<String> dictionary = readFileIntoSet("your_dictionary_file");

Then, after you find the reversed word, check that it appears in the dictionary:

if (dictionary.contains(reverseWord))
   system.out.println("this word: " + reverseWord + " appears in the dictionary!");

Please also note that the String class offers a "reverse" method. Thus, you can get rid of the for(int i = wordLength-1; i >= 0; i--){ ... } loop and just use reverseWord = foundWord.reverse();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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