Advertisement
alyoshinkkaa

Untitled

Aug 1st, 2023
31
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.86 KB | None | 0 0
  1. import java.io.BufferedReader;
  2. import java.io.BufferedWriter;
  3. import java.io.FileInputStream;
  4. import java.io.InputStreamReader;
  5. import java.io.Reader;
  6. import java.io.IOException;
  7. import java.io.OutputStreamWriter;
  8. import java.io.FileOutputStream;
  9. import java.io.FileNotFoundException;
  10. import java.lang.String;
  11. import java.util.Map;
  12. import java.util.TreeMap;
  13.  
  14. public class WordStatWordsShingles {
  15. public static void addWord(Map<String, Integer> words, String word) {
  16. if (word.length() > 0) {
  17. // :NOTE: it is enough to use .put and .getOrDefault (see the implementation of .replace method)
  18. words.replace(word, words.get(word), words.getOrDefault(word, words.putIfAbsent(word, 1)) + 1);
  19. }
  20. }
  21. public static void main(String[] args) {
  22. // :NOTE: a variable name always starts with a lowercase letter
  23. final int MaxWordLength = 3;
  24. Map<String, Integer> words = new TreeMap<>();
  25. try {
  26. Reader reader = new BufferedReader(new InputStreamReader(
  27. new FileInputStream(args[0])
  28. ));
  29. try {
  30. char symbol;
  31. StringBuilder word = new StringBuilder();
  32. int read = reader.read();
  33. symbol = (char) read;
  34. while (read > -1) {
  35. if (Character.isLetter(symbol) || symbol == '\'' || Character.DASH_PUNCTUATION == Character.getType(symbol)) {
  36. word.append(symbol);
  37. if (word.length() >= MaxWordLength) {
  38. addWord(words, word.toString().toLowerCase().substring(word.length() - MaxWordLength, word.length()));
  39. }
  40. } else {
  41. if (word.length() < MaxWordLength) {
  42. addWord(words, word.toString().toLowerCase());
  43. }
  44. word.delete(0, word.length());
  45. }
  46. read = reader.read();
  47. symbol = (char) read;
  48. }
  49. } finally {
  50. reader.close();
  51. }
  52. BufferedWriter writer = new BufferedWriter(
  53. new OutputStreamWriter(
  54. new FileOutputStream(args[1])
  55. )
  56. );
  57. try {
  58. for (Map.Entry<String, Integer> output : words.entrySet()) {
  59. writer.write(output.getKey() + " " + output.getValue() + System.lineSeparator());
  60. }
  61. } finally {
  62. writer.close();
  63. }
  64. } catch (FileNotFoundException e) {
  65. System.out.println("File not found: " + e.getMessage());
  66. } catch (IOException e) {
  67. System.out.println("I/O Exception: " + e.getMessage());
  68. }
  69. }
  70. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement