Skip to content

Instantly share code, notes, and snippets.

@sorami
Last active June 22, 2021 10:50
Show Gist options
  • Save sorami/bde9d441a147e0fc2e6e5fdd83f4f770 to your computer and use it in GitHub Desktop.
Save sorami/bde9d441a147e0fc2e6e5fdd83f4f770 to your computer and use it in GitHub Desktop.
Sudachi Character Normalization; cf. https://zenn.dev/sorami/articles/6bdb4bf6c7f207/
This is free and unencumbered software released into the public domain.
Anyone is free to copy, modify, publish, use, compile, sell, or
distribute this software, either in source code form or as a compiled
binary, for any purpose, commercial or non-commercial, and by any
means.
In jurisdictions that recognize copyright laws, the author or authors
of this software dedicate any and all copyright interest in the
software to the public domain. We make this dedication for the benefit
of the public at large and to the detriment of our heirs and
successors. We intend this dedication to be an overt act of
relinquishment in perpetuity of all present and future rights to this
software under copyright law.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.
For more information, please refer to <http://unlicense.org/>
import sys
import unicodedata
class SudachiCharNormalizer:
def __init__(self, rewrite_def_path="./rewrite.def"):
self.ignore_normalize_set = set()
self.replace_char_map = {}
self.read_rewrite_def(rewrite_def_path)
def read_rewrite_def(self, rewrite_def_path):
with open(rewrite_def_path, encoding="utf8") as f:
for i, line in enumerate(f):
line = line.strip()
if line.startswith("#") or not line:
continue
cols = line.split()
if len(cols) == 1:
if len(cols[0]) != 1:
raise Exception("'{}' is not a single character at line {}".format(cols[0], i))
self.ignore_normalize_set.add(cols[0])
elif len(cols) == 2:
if cols[0] in self.replace_char_map:
raise Exception("'Replacement for '{}' defined again at line {}".format(cols[0], i))
self.replace_char_map[cols[0]] = cols[1]
else:
raise Exception("Invalid format '{}' at line {}".format(line, i))
def rewrite(self, text):
chars_after = []
offset = 0
next_offset = 0
i = -1
while True:
i += 1
if i >= len(text):
break
textloop = False
offset += next_offset
next_offset = 0
# 1. replace char without normalize
for l in range(len(text) - i, 0, -1):
replace = self.replace_char_map.get(text[i:i+l])
if replace:
chars_after.append(replace)
next_offset += len(replace) - l
i += l - 1
textloop = True
continue
if textloop:
continue
# 2. normalize
# 2-1. capital alphabet (not only latin but greek, cyrillic, etc) -> small
original = text[i]
lower = original.lower()
if lower in self.ignore_normalize_set:
replace = lower
else:
# 2-2. normalize (except in ignoreNormalize)
# e.g. full-width alphabet -> half-width / ligature / etc.
replace = unicodedata.normalize("NFKC", lower)
next_offset = len(replace) - 1
chars_after.append(replace)
return "".join(chars_after)
if __name__ == "__main__":
if len(sys.argv) == 2:
normalizer = SudachiCharNormalizer(sys.argv[1])
else:
normalizer = SudachiCharNormalizer()
for line in sys.stdin:
print(normalizer.rewrite(line.strip()))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment