Java文字外观在文本文件中

时间:2017-12-09 17:36:40

标签: java oop

对于给定的文本文件(text.txt),计算每个单词在文件中出现的次数。程序的输出应该是另一个文本文件,每行包含一个单词,然后是它在原始文件中出现的次数。完成更改程序后,输出文件中的单词将按字母顺序排序。不要使用地图,只使用基本数组。这个东西只显示我在该文本文件中从键盘输入的一个单词,但是如何显示所有单词,而不仅仅是一个单词?感谢

package worddata;
import java.io.IOException;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

 class WordData {
     public FileReader fr = null;
     public BufferedReader br =null;

     public String [] stringArray;
     public int counLine = 0;
     public int arrayLength ;
      public String s="";
    public String stringLine="";
     public String filename ="";
     public String wordname ="";

public WordData(){

    try{
        Scanner scan = new Scanner(System.in);
        System.out.println("Please enter the filename: ");
        filename = scan.nextLine();
        Scanner scan2 = new Scanner(System.in);
        System.out.println("Please enter a word: ");
        wordname = scan.nextLine();
        fr = new FileReader(filename);
        br = new BufferedReader(fr);
        while((s = br.readLine()) != null){
            stringLine = stringLine + s;
            //System.out.println(s);
            stringLine = stringLine + " ";
            counLine ++;
        }





        stringArray = stringLine.split(" ");
        arrayLength = stringArray.length;
        for (int i = 0; i < arrayLength; i++) {
            int c = 1 ;
            for (int j = i+1; j < arrayLength; j++) {
                if(stringArray[i].equalsIgnoreCase(stringArray[j])){
                    c++;
                    for (int j2 = j; j2 < arrayLength; j2++) {
                        stringArray[j2] = stringArray[j2+1];
                        arrayLength = arrayLength - 1;
                    }

                       if (stringArray[i].equalsIgnoreCase(wordname)){
           System.out.println("The word "+wordname+" is present "+c+" times in the specified file.");
           }
                }
        }
    }
        System.out.println("Total number of lines: "+counLine);
        fr.close();
        br.close();
    }catch (Exception e) {
        e.printStackTrace();
    }
}
public static void main(String[] args) throws IOException {
    Scanner scan = new Scanner(System.in);
    OutputStream out = new FileOutputStream("output.txt");
    System.out.println("Please enter the filename: ");
    String filename = scan.nextLine();
    System.out.println("Please enter a word: ");
    String wordname = scan.nextLine();
    int count = 0;
    try (LineNumberReader r = new LineNumberReader(new FileReader(filename))) {
        String line;
        while ((line = r.readLine()) != null) {
            for (String element : line.split(" ")) {
                if (element.equalsIgnoreCase(wordname)) {
                    count++;
                    System.out.println("Word found at line " + r.getLineNumber());
                }
            }
        }
    }
                        FileReader fileReader = new FileReader(filename);
            BufferedReader bufferedReader = new BufferedReader(fileReader);
            StringBuffer stringBuffer = new StringBuffer();
            String line;
            while ((line = bufferedReader.readLine()) != null) {
                stringBuffer.append(line);
                stringBuffer.append("\n");
            }
            fileReader.close();
    System.out.println("The word " + stringBuffer.toString() + " appears " + count + " times.");
    int i;
    List<String> ls = new ArrayList<String>();
    for (i = 1; i <= 1000; i++) {
        String str = null;
        str = +i + ":-  The word "+wordname+" was found " + count +"  times";
        ls.add(str);
    }
    String listString = "";
    for (String s : ls) {
        listString += s + "\n";
    }
    FileWriter writer = null;
    try {
        writer = new FileWriter("final.txt");
        writer.write(listString);
        writer.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
}
}

1 个答案:

答案 0 :(得分:0)

下面的代码就像你想要的那样。

它执行以下操作:

  • 阅读input.txt文件
  • 中的内容
  • 从文字中删除标点符号
  • 通过删除换行符使其成为一串字词
  • 使用空格作为分隔符
  • 将文本拆分为单词
  • lambda将所有单词映射为小写,然后删除空格和所有空条目,然后它......
  • 遍历所有单词并计算het HashMap中的单词计数
  • 然后我们按相反顺序对计数值进行排序,以获得最高计数单词
  • 然后将它们写入StringBuilder,将其格式化为&#34; word:count \ n&#34;然后将其写入文本文件

    final String content = new String(Files.readAllBytes(Paths.get("<PATH TO YOUR PLACE>/input.txt")));
    final List<String> words = Arrays.asList(content.replaceAll("[\\p{InCombiningDiacriticalMarks}]", "").replace("\n", " ").split(" "));
    
    final Map<String, Integer> wordlist = new HashMap<>();
    words.stream()
            .map(String::toLowerCase)
            .map(String::trim)
            .filter(s -> !s.isEmpty())
            .forEach(s -> {
                wordlist.computeIfPresent(s, (s1, integer) -> ++integer);
                wordlist.putIfAbsent(s, 1);
            });
    
    final StringBuilder sb = new StringBuilder();
    wordlist.entrySet()
            .stream()
            .sorted(Map.Entry.comparingByValue(Collections.reverseOrder()))
            .collect(Collectors.toMap(
                    Map.Entry::getKey,
                    Map.Entry::getValue,
                    (e1, e2) -> e1,
                    LinkedHashMap::new
            )).forEach((s, integer) -> sb.append(s).append(" : ").append(integer).append("\n"));
    
    Files.write(Paths.get("<PATH TO YOUR PLACE>/output.txt"), sb.toString().getBytes());
    

希望它有所帮助: - )

注意:<PATH TO YOUR PLACE>需要替换为包含文字的文本文件的完全限定路径。