-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathparser.rb
More file actions
84 lines (67 loc) · 1.54 KB
/
parser.rb
File metadata and controls
84 lines (67 loc) · 1.54 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
##
# This Parser counts the number of words in a file (or files in a directory)
#
# myParser = Parser.new
#
# myParser.debug = true
# myParser.minlen = 3
# myParser.wordchars = 'a-z0-9'
#
# myParser.read('file')
#
# puts myParser.words_asc
# puts myParser.words_desc
class Parser
attr_reader :words
attr_accessor :debug
attr_accessor :minlen
attr_accessor :wordchars
def initialize(*args)
@words = {}
@debug = false
@minlen = 3
@wordchars = 'a-z0-9'
end
# Sorts the words hash by appearance count and returns it in ascending order
#
def words_asc
return @words.sort {|a1,a2| a1[1].to_i <=> a2[1].to_i }.to_h
end
# Sorts the words hash by appearance count and returns it in descending order
#
def words_desc
return @words.sort {|a1,a2| a2[1].to_i <=> a1[1].to_i }.to_h
end
# Given a file or filepath read the data into the words hash
#
def read(item)
if File.directory?(item)
Dir.foreach(item) do |nxt|
next if nxt == '.' or nxt == '..'
read("#{item}/#{nxt}")
end
else
read_one(item)
end
end
private
# read_one is a private method that actually (and only reads a single file)
#
def read_one(file)
if @debug then puts "Reading #{file}" end
fileObj = File.new(file, "r")
while (line = fileObj.gets)
line = line.unpack("C*").pack("U*").downcase
line.gsub!(/[^#{wordchars}]/, ' ')
line.split(" ").each do |word|
next if word.length < @minlen
if @words.has_key?(word)
@words[word] = @words[word] + 1
else
@words[word] = 1
end
end
end
fileObj.close
end
end