Class: String

Inherits:
Object
  • Object
show all
Defined in:
lib/normalize_text/normalize_text.rb

Instance Method Summary collapse

Instance Method Details

#normalizeObject



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
# File 'lib/normalize_text/normalize_text.rb', line 2

def normalize
  text = self

  text = text.gsub(/(?![\r\n])[[:cntrl:]]/, '')
  text = text.gsub(/\r\n/, ' ').gsub(/[\n|\r]/, ' ')

  text = RemoveEmoji::Sanitize.call(text)
  text = text.each_char.select { |c| c.bytes.count < 4 }.join

  text = text.unicode_normalize(:nfkc)

  hypon_reg = /(?:˗|֊|‐|‑|‒|–|⁃|⁻|₋|−)/
  text = text.gsub(hypon_reg, '-')

  choon_reg = /(?:﹣|-|ー|—|―|─|━)/
  text = text.gsub(choon_reg, '')
  text = text.gsub(/ー+/, '')

  chil_reg = /(?:~|∼|∾|〜|〰|~)/
  text = text.gsub(chil_reg, '')

  text = text.tr(%q{!"#$%&'()*+,-.\/:;<=>?@[¥]^_`{|}~。、・「」"},
                 '!”#$%&’()*+,-./:;<=>?@[¥]^_`{|}〜。、・「」')

  text = text.gsub(/ /, ' ')
  text = text.gsub(/ {1,}/, ' ')
  text = text.gsub(/^ +(.+?)$/, '\\1')
  text = text.gsub(/^(.+?) +$/, '\\1')

  while text =~ /([\p{InCjkUnifiedIdeographs}\p{InHiragana}\p{InKatakana}\p{InHalfwidthAndFullwidthForms}\p{InCJKSymbolsAndPunctuation}]+?) {1}([\p{InCjkUnifiedIdeographs}\p{InHiragana}\p{InKatakana}\p{InHalfwidthAndFullwidthForms}\p{InCJKSymbolsAndPunctuation}]+?)/
    text = text.gsub(
      /([\p{InCJKUnifiedIdeographs}\p{InHiragana}\p{InKatakana}\p{InHalfwidthAndFullwidthForms}\p{InCJKSymbolsAndPunctuation}]+?) {1}([\p{InCJKUnifiedIdeographs}\p{InHiragana}\p{InKatakana}\p{InHalfwidthAndFullwidthForms}\p{InCJKSymbolsAndPunctuation}]+?)/, '\\1\\2'
    )
  end

  while text =~ /(\p{InBasicLatin}+) {1}([\p{InCJKUnifiedIdeographs}\p{InHiragana}\p{InKatakana}\p{InHalfwidthAndFullwidthForms}\p{InCJKSymbolsAndPunctuation}]+)/
    text = text.gsub(
      /(\p{InBasicLatin}+) {1}([\p{InCJKUnifiedIdeographs}\p{InHiragana}\p{InKatakana}\p{InHalfwidthAndFullwidthForms}\p{InCJKSymbolsAndPunctuation}]+)/, '\\1\\2'
    )
  end

  while text =~ /([\p{InCJKUnifiedIdeographs}\p{InHiragana}\p{InKatakana}\p{InHalfwidthAndFullwidthForms}\p{InCJKSymbolsAndPunctuation}]+) {1}(\p{InBasicLatin}+)/
    text = text.gsub(
      /([\p{InCJKUnifiedIdeographs}\p{InHiragana}\p{InKatakana}\p{InHalfwidthAndFullwidthForms}\p{InCJKSymbolsAndPunctuation}]+) {1}(\p{InBasicLatin}+)/, '\\1\\2'
    )
  end

  text.tr(
    '!”#$%&’()*+,-./:;<>?@[¥]^_`{|}〜',
    %q{!"#$%&'()*+,-.\/:;<>?@[¥]^_`{|}~}
  )
end