Compile regex patterns once

Signed-off-by: TheJackiMonster <thejackimonster@gmail.com>
This commit is contained in:
TheJackiMonster 2023-02-03 05:39:47 +01:00
parent eac2964330
commit e368cc7f73
No known key found for this signature in database
GPG key ID: D850A5F772E880F9

View file

@ -5,6 +5,10 @@ import re
from enum import Enum, unique
_char_pattern_with_spaces = re.compile(r"[\S ]")
_char_pattern_without_spaces = re.compile(r"\S")
_word_pattern = re.compile(r"\S+")
@unique
class CounterKind(Enum):
@ -18,16 +22,16 @@ class CharCounter:
@classmethod
def count(cls, text: str, use_spaces: bool = False):
if use_spaces:
return len(re.findall(r"[\S ]", text))
return len(_char_pattern_with_spaces.findall(text))
else:
return len(re.findall(r"\S", text))
return len(_char_pattern_without_spaces.findall(text))
class WordCounter:
@classmethod
def count(cls, text: str):
return len(re.findall(r"\S+", text))
return len(_word_pattern.findall(text))
class PageCounter: