Implementation as class

This commit is contained in:
Patrick Elmer 2023-01-29 10:05:48 +09:00
commit dd5b8ea1d5
6 changed files with 60 additions and 0 deletions

1
.gitignore vendored Normal file
View File

@ -0,0 +1 @@
.pytest*

3
README.md Normal file
View File

@ -0,0 +1,3 @@
# SoundChanger
Applies sound changes to words.

Binary file not shown.

32
soundchanger.py Normal file
View File

@ -0,0 +1,32 @@
import re
class Change:
"""
Instantiates a string representation of a sound change.
"""
def __init__(self, change):
self.parse(change)
def __repr__(self):
return f"{self.b}>{self.a}/{self.f}_{self.t}"
def parse(self, change):
if '/' in change:
_change, _env = change.split('/')
else:
_change = change
_env = '_'
self.b, self.a = _change.split('>')
self.f, self.t = _env.split('_')
if self.f.startswith("{") and self.f.endswith("}"):
self.f = self.f[1:-1].split(',')
self.f = f"[{''.join(self.f)}]"
if self.t.startswith("{") and self.t.endswith("}"):
self.t = self.t[1:-1].split(',')
self.t = f"[{''.join(self.t)}]"
def sub(self, string):
return re.sub(f"(?<={self.f}){self.b}(?={self.t})", f"{self.a}", f"#{string}#").strip('#')

24
tests/test_apply.py Normal file
View File

@ -0,0 +1,24 @@
from soundchanger import Change
def test_simple_change_without_environment():
c = Change('p>f')
assert c.sub('pana') == 'fana'
assert c.sub('kapa') == 'kafa'
def test_simple_change_with_environment():
c = Change('p>f/#_a')
assert c.sub('pana') == 'fana'
assert c.sub('pune') == 'pune'
assert c.sub('kapa') == 'kapa'
def test_complex_change_with_environment():
c = Change('p>f/{#,a}_{a,u}')
assert c.sub('pana') == 'fana'
assert c.sub('pune') == 'fune'
assert c.sub('kapa') == 'kafa'
# def test_simple_change_with_category():
# c = Change('w>h/V_V')
# assert c.sub('kawa') == 'kaha'
# assert c.sub('tuwo') == 'tuho'