Added string replacement function for future use
This commit is contained in:
2
.gitignore
vendored
2
.gitignore
vendored
@ -166,6 +166,6 @@ cython_debug/
|
||||
.vscode
|
||||
|
||||
# Debugging files
|
||||
debug.py
|
||||
debug*.py
|
||||
test.py
|
||||
|
||||
|
||||
15
examples/music21_example.py
Normal file
15
examples/music21_example.py
Normal file
@ -0,0 +1,15 @@
|
||||
from music21 import *
|
||||
from sardine import *
|
||||
from ziffers import *
|
||||
|
||||
|
||||
s = to_music21('i v vi vii^dim',time="4/4")
|
||||
|
||||
s.show()
|
||||
s.show('midi')
|
||||
|
||||
parsed = zparse('1 2 qr e 124')
|
||||
s2 = to_music21(parsed,time="4/4")
|
||||
|
||||
s2.show()
|
||||
s2.show('midi')
|
||||
@ -27,6 +27,9 @@ homepage = "https://github.com/Bubobubobubobubo/ziffers-python"
|
||||
documentation = "https://github.com/Bubobubobubobubo/ziffers-python"
|
||||
repository = "https://github.com/Bubobubobubobubo/ziffers-python"
|
||||
|
||||
[tool.setuptools]
|
||||
py-modules = ['ziffers']
|
||||
|
||||
[tool.black]
|
||||
target_version = ['py311']
|
||||
include = '\.pyi?$'
|
||||
|
||||
10
test.py
10
test.py
@ -1,10 +0,0 @@
|
||||
from music21 import *
|
||||
from sardine import *
|
||||
from ziffers import *
|
||||
|
||||
a = zparse('1 2 qr 124')
|
||||
print(list(a))
|
||||
s = to_music21('1 2 qr 124',octave=-2,time="3/4")
|
||||
|
||||
s.show()
|
||||
s.show('midi')
|
||||
@ -1,9 +1,13 @@
|
||||
""" Common methods used in parsing """
|
||||
import re
|
||||
|
||||
|
||||
def flatten(arr: list) -> list:
|
||||
"""Flattens array"""
|
||||
return (
|
||||
flatten(arr[0]) + (flatten(arr[1:]) if len(arr) > 1 else [])
|
||||
if isinstance(arr, list) else [arr]
|
||||
if isinstance(arr, list)
|
||||
else [arr]
|
||||
)
|
||||
|
||||
|
||||
@ -17,4 +21,35 @@ def sum_dict(arr: list[dict]) -> dict:
|
||||
else:
|
||||
result[key] = element[key]
|
||||
return result
|
||||
|
||||
|
||||
|
||||
def string_rewrite(axiom: str, rules: dict):
|
||||
"""String rewrite / Lindemeyer system for rule based text manipulation
|
||||
|
||||
Args:
|
||||
axiom (str): Input string
|
||||
rules (dict): String manipulation rules in dict:
|
||||
|
||||
Example:
|
||||
rules = {
|
||||
"1": "2",
|
||||
"[2-9]": "45",
|
||||
"4": lambda: str(randint(1, 7)),
|
||||
"([1-9])(5)": lambda a, b: str(int(a)*int(b))
|
||||
}
|
||||
|
||||
for i range(10):
|
||||
print(string_rewrite("1", rules))
|
||||
"""
|
||||
|
||||
def _apply_rules(match):
|
||||
for key, value in rules.items():
|
||||
if re.match(key, match.group(0)):
|
||||
if callable(value):
|
||||
yield value(
|
||||
*match.groups()
|
||||
) if value.__code__.co_argcount > 0 else value()
|
||||
yield value
|
||||
|
||||
pattern = re.compile("|".join(rules.keys()))
|
||||
return pattern.sub(lambda m: next(_apply_rules(m)), axiom)
|
||||
|
||||
Reference in New Issue
Block a user