Guest User

Untitled

a guest
Dec 16th, 2018
107
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.29 KB | None | 0 0
  1. #!/usr/bin/ruby
  2. #CS132A - Ruby - Lab 3 - Text Analyzer
  3. #Author: Zach
  4. #Purpose: Utilize Ruby File.class to analyze Text files
  5. # and generate statitical information therein.
  6.  
  7.  
  8. STOPWORDS = IO.readlines('stop_words.txt').map {|i| i.chomp}
  9.  
  10. your_text_files = Dir.glob("*.txt")
  11.  
  12. your_text_files.each do |text_file|
  13.  
  14. # Local Variables / Text Files
  15. line_count = text_file.size
  16. text = File.read(text_file)
  17.  
  18. # Count the characters
  19. tot_chars = text.length
  20. tot_chars_no_space = text.gsub(/\s+/, '').length
  21.  
  22. # Count the words, sentences and paragraphs
  23. word_count = text.split.length
  24. sent_count = text.split(/\.|\?|!/).length
  25. para_count = text.split(/\n\n/).length
  26.  
  27. # Stop Words Processing
  28. puts "Meaningful Words"
  29. puts
  30. keywords = text.split(/\s+/).select {|word| !STOPWORDS.include?(word)}
  31. puts keywords.join(' ')
  32. good_percent = ((keywords.length.to_f / word_count.to_f) * 100).to_i
  33.  
  34. # Ideal Sentences
  35. puts "Ideal sentences from text"
  36. sentences = text.gsub(/\s+/, ' ').strip.split(/\.|\?|!/)
  37. sentences_sorted = sentences.sort_by { |sentence| sentence.length }
  38. foo = sentences_sorted.length / 7
  39. ideal_sentences = sentences_sorted.slice(foo, foo + 1)
  40. ideal_sentences = ideal_sentences.select { |sentence| sentence =~/\sis\W|\sare\W/ }
  41. puts
  42.  
  43. # Common Words
  44. puts "10 Most common words from text"
  45. words_less_stop = (keywords - STOPWORDS).group_by{ |x| x}.sort_by{ |word, hits| -hits.length}[0..9].map(&:first)
  46. puts words_less_stop
  47. puts
  48.  
  49. # Output Statements
  50. puts "Innagural Speech Statistics"
  51. puts "The total number of lines in the inaugural speech is #{line_count}\."
  52. puts "The total number of characters in the first part is #{tot_chars}\."
  53. puts "The total number of characters less whitespace is #{tot_chars_no_space}\."
  54. puts "The total number of words is #{word_count}\."
  55. puts "The total number of sentences is #{sent_count}\."
  56. puts "The total number of paragraphs is #{para_count}\."
  57. puts "The average sentences per paragraph is #{sent_count/para_count}\."
  58. puts "The average words per sentence is #{word_count/ sent_count}\."
  59. puts "#{good_percent}% of all words in the text are non-fluff words."
  60. puts
  61. puts "The ideal sentences are:\n\n" + ideal_sentences.join(". ")
  62. puts
  63.  
  64. end
Add Comment
Please, Sign In to add comment