dict 値を取得しようとしたときに無効な文字を置き換えるための単純なデコレータがあります。
import types
class ContentInterface(dict):
def __getitem__(self, item):
raise NotImplementedError
class Content(ContentInterface):
def __getitem__(self, item):
return dict.__getitem__(self, item)
class DictDecorator(ContentInterface):
def __init__(self, interfaceContent, **config):
super(DictDecorator, self).__init__()
self._component = interfaceContent
self._config = config
def _replace(self, text):
return text
def _check(self, invalidCharacterSet, itemPath):
pass
def __getitem__(self, name):
item = self._component[name]
if isinstance(item, types.StringTypes):
newText = self._replace(item)
invalidCharacterSet = set([char for char in item if char not in newText])
self._check(invalidCharacterSet, name)
return newText
else:
return self.__class__(item, **self._config)
class ReplaceCommaDecorator(DictDecorator):
def _replace(self, text):
return text.replace(",", ' ')
class ReplaceDotDecorator(DictDecorator):
def _replace(self, text):
return text.replace('.', ' ')
class ReplaceColonDecorator(DictDecorator):
def _replace(self, text):
return text.replace(":", ' ')
class ReplaceSemicolonDecorator(DictDecorator):
def _replace(self, text):
return text.replace(";", ' ')
これを次のように使用したい:
dictWithReplacedCharacters =\
ReplaceCommaDecorator( # Empty
ReplaceDotDecorator( # Empty
ReplaceColonDecorator( # Empty
ReplaceSemicolonDecorator( # Empty
Content({ # Data
'1':u'1A:B;C,D.E',
'2':{
'21':u'21A:B;C,D.E',
'22':u'22A:B;C,D.E',
}
}),
),
),
),
)
print dictWithReplacedCharacters['2']['21']
1 つのデータ dict のデコレータを表す 4 つの冗長な dict オブジェクトがあります。
上記のネストされたステートメントが、データを含む Content から継承された ReplaceSemicolonDecorator から継承された ReplaceColonDecorator から継承された ReplaceDotDecorator から継承された ReplaceCommaDecorator オブジェクトを返すように強制したいと考えています。これは DictDecorator の __new__ メソッドで解決できると思います。