I am working to improve this script, which should prepare a text to be sent as a GSM short message using only the GSM 7-bit character coding with Basic Character Set Extension.
import logging
import traceback
import unicodedata
logger = logging.getLogger(__name__)
class IsGSM:
def __init__(self):
self.gsm = "@£$¥èéùìòÇ\nØø\rÅåΔ_ΦΓΛΩΠΨΣΘΞ\x1bÆæßÉ !\"#¤%&'()*+,-./0123456789:;<=>?" \
"¡ABCDEFGHIJKLMNOPQRSTUVWXYZÄÖÑܧ¿abcdefghijklmnopqrstuvwxyzäöñüà"
self.ext = "^{}\\[~]|€"
self.toBeNormalized = '\xa0'+'\xc2'
self.ascii_gsm = {}
self.ascii_map()
self.normalize_dict = {}
self.normalize_map()
def ascii_map(self):
for c in self.gsm:
#if ord(c) < 256:
self.ascii_gsm[ord(c)] = True
for c in self.ext:
#if ord(c) < 256:
self.ascii_gsm[ord(c)] = True
def normalize_map(self):
for c in self.toBeNormalized:
self.normalize_dict[c] = True
def _is_gsm(self, content):
template = content
try:
template.encode('windows-1252')
except UnicodeEncodeError:
return False
for c in content:
if ord(c) not in self.ascii_gsm:
return False
return True
@classmethod
def is_gsm(cls, content):
instance = IsGSM.instance()
return instance._is_gsm(content)
@classmethod
def normalizeBodyContent(cls, content):
instance = IsGSM.instance()
return instance._normalizeBodyContent(content)
@classmethod
def instance(cls):
"""Singleton like accessor to instantiate backend object"""
if not hasattr(cls, "_instance"):
cls._instance = cls()
return cls._instance
def _normalizeBodyContent(self, content):
try:
target_content = [c for c in content]
content_length = len(target_content)
for ith in range(content_length):
if target_content[ith] in self.normalize_dict:
target_content[ith] = unicodedata.normalize("NFKD",target_content[ith])
content = "".join(target_content)
except Exception as e:
logger.error('Exception occurred normalizing content {0}'.format(content))
traceback.print_exc()
raise e
return content
if __name__ == "__main__":
print(IsGSM.is_gsm("Est a punto de restablecer la contrasea de su cartera de Kutxabank. Por favor, introduzca la sigui..."))
print(IsGSM.is_gsm("This should fix the problem. Your content xxxxx from ÄA K COMPANY LTD will be delivered by xxxx today.Track your content at some_url@&!"))
I can refactor the _normalizeBodyContent
method like this:
def _normalizeBodyContent(self, content):
try:
target_content = [c for c in content]
content_length = len(target_content)
for ith in self.normalize_dict:
target_content = target_content.replace(ith,
unicodedata.normalize("NFKD", ith))
content = "".join(target_content)
except Exception as e:
logger.error('Exception occurred normalizing content {0}'.format(content))
traceback.print_exc()
raise e
return content
Is this an improvement on the original, in-terms of processing time and readability?
I'm particularly interested in comparing the lookup via in
and overwrite against using the replace()
library function. Review on any portion of the whole script is also appreciated.