|
| 1 | +require "json" |
| 2 | +require "yaml" |
| 3 | + |
| 4 | +# TODO: Write documentation for `FastWordsCr` |
| 5 | + |
| 6 | +module Example::Crystal |
| 7 | + VERSION = "0.2.0" |
| 8 | + CHARSET = "aąbcćdeęfghijklłmnńoópqrsśtuvwxyzźż" |
| 9 | + |
| 10 | + def self.main(outpath = "words") |
| 11 | + with_sorting = false |
| 12 | + concurrent = true |
| 13 | + |
| 14 | + prepare_folder(outpath, "*.txt") |
| 15 | + |
| 16 | + file_count = 0 |
| 17 | + total_size = 0 |
| 18 | + |
| 19 | + channel = Channel(Tuple(String, Int64)).new |
| 20 | + srcPath = "../data/??/**/*.yml" |
| 21 | + # srcPath = "./bibles/??/**/*.yml" |
| 22 | + Dir.glob(srcPath, follow_symlinks: true).each do |path| |
| 23 | + if concurrent |
| 24 | + spawn do |
| 25 | + channel.send worker(path, outpath, with_sorting) |
| 26 | + end |
| 27 | + file_count += 1 |
| 28 | + else |
| 29 | + worker(path, outpath, with_sorting) |
| 30 | + end |
| 31 | + end |
| 32 | + if concurrent |
| 33 | + file_count.times do |i| |
| 34 | + path, size = channel.receive |
| 35 | + total_size += size |
| 36 | + # puts("[#{i + 1}/#{file_count}] #{path}") |
| 37 | + end |
| 38 | + end |
| 39 | + total_size = total_size / 1024 / 1024 |
| 40 | + puts("Total size: #{total_size} MB") |
| 41 | + end |
| 42 | + |
| 43 | + def self.worker(path, outpath, with_sorting) |
| 44 | + filepath = path.gsub(".yml", ".txt") |
| 45 | + text = File.read(filepath).gsub("\n", " ").downcase |
| 46 | + |
| 47 | + words = text.split(/[^\p{L}]+/).to_set |
| 48 | + |
| 49 | + if with_sorting |
| 50 | + words = words.to_a.sort { |x, y| self.word_cmp(x, y) } |
| 51 | + end |
| 52 | + |
| 53 | + meta = File.open(path) { |file| YAML.parse(file) } |
| 54 | + filepath = %Q(#{outpath}/#{meta["lang"]}-#{meta["code"]}.txt) |
| 55 | + File.write(filepath, words.join("\n")) |
| 56 | + filesize = File.size(filepath) |
| 57 | + puts([filepath, filesize]) |
| 58 | + {filepath, filesize} |
| 59 | + end |
| 60 | + |
| 61 | + def self.prepare_folder(folder : String, pattern : String) |
| 62 | + Dir.mkdir_p(folder) unless File.exists?(folder) |
| 63 | + Dir.glob("#{folder}/#{pattern}").each do |path| |
| 64 | + File.delete path |
| 65 | + end |
| 66 | + end |
| 67 | + |
| 68 | + def self.word_cmp(str1 : String, str2 : String) |
| 69 | + tokens2 = str2.chars |
| 70 | + str1.chars.each_with_index do |s1, i| |
| 71 | + return 1 unless tokens2[i]? |
| 72 | + idx1 = CHARSET.index(s1) || -1 |
| 73 | + idx2 = CHARSET.index(tokens2[i]) || -1 |
| 74 | + return 1 if idx1 > idx2 |
| 75 | + return -1 if idx1 < idx2 |
| 76 | + end |
| 77 | + 0 |
| 78 | + end |
| 79 | +end |
| 80 | + |
| 81 | +elapsed_time = Time.measure do |
| 82 | + Example::Crystal.main |
| 83 | +end |
| 84 | +puts elapsed_time |
0 commit comments