Skip to content

Commit

Permalink
Refactor name parser
Browse files Browse the repository at this point in the history
  • Loading branch information
Splines committed Mar 15, 2024
1 parent 9952a1a commit 6ae7c55
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 27 deletions.
35 changes: 8 additions & 27 deletions src/api/parsers.py
Original file line number Diff line number Diff line change
Expand Up @@ -33,48 +33,29 @@ def parse_name(name: str) -> str:
)

parsed_name = ""
next_chat_upper = False

next_char_upper = False
ignored_chars = set()

while name != "":
char = name[0]

if char.isalpha():
if next_chat_upper:
if next_char_upper:
parsed_name += char.upper()
next_chat_upper = False
next_char_upper = False
else:
parsed_name += char
elif char.isdigit():
# Count number of digits:
num_of_digits = 0
for c in name:
if c.isdigit():
num_of_digits += 1
else:
break

# Turn digits into word(s):
word = ""
if num_of_digits <= 3:
word += Helpers.number_to_word(int(name[:num_of_digits]))
else:
word += Helpers.number_to_word(int(name[0]))
for i in range(1, num_of_digits):
word += Helpers.capitalize((Helpers.number_to_word(int(name[i]))))

# Add word to parsed_name:
num_digits = len([c for c in name if c.isdigit()]) # greedily get digits
word = Helpers.digit_str_to_word(name[:num_digits])
if parsed_name != "":
word = Helpers.capitalize(word)
parsed_name += word
next_chat_upper = True

# Skip the digits:
name = name[num_of_digits:]
next_char_upper = True
name = name[num_digits:] # Skip the parsed digits
continue
elif char in [" ", "_", "-"]:
next_chat_upper = True
next_char_upper = True
else:
ignored_chars.add(char)

Expand Down
17 changes: 17 additions & 0 deletions src/application/helpers.py
Original file line number Diff line number Diff line change
Expand Up @@ -68,3 +68,20 @@ def number_to_word(cls, number: int) -> str:
@classmethod
def capitalize(cls, s: str) -> str:
return s[0].upper() + s[1:]

@classmethod
def digit_str_to_word(cls, digits_str: str) -> str:
"""Converts a string of digits to a word.
For example, "123" -> "oneHundredTwentyThree",
"911" -> "nineHundredEleven".
"""
num_digits = len(digits_str)
if num_digits <= 3:
return cls.number_to_word(int(digits_str))

word = cls.number_to_word(int(digits_str[0]))
for i in range(1, num_digits):
tmp = Helpers.number_to_word(int(digits_str[i]))
word += Helpers.capitalize(tmp)
return word

0 comments on commit 6ae7c55

Please sign in to comment.