Avoid manually decoding many lines in code

I work in Python. Since I have to bet .decode('utf-8')very often, I would like it to be automatically decoded.

  • Is there a way to make all the lines decoded with utf-8 automatically?

And the second question:

  • Is there a flaw?

PS: I need to decode especially strings where diacritics appear as "Čečensko"

Here is an example:

result={}
if 'Ulice: ' in spans.keys():
    result['ulica']=spans['Ulice: ']
else:
    result['ulica']=''
if 'Kontaktní osoba: '.decode('utf-8') in spans.keys():
    result['kontaktna osoba']=spans['Kontaktní osoba: '.decode('utf-8')]
else:
    result['kontaktna osoba']=''
if 'Město: '.decode('utf-8') in spans.keys():
    result['mesto']=spans['Město: '.decode('utf-8')]
else:
    result['mesto']=''
if 'PSČ: '.decode('utf-8') in spans.keys():
    result['psc']=spans['PSČ: '.decode('utf-8')]
else:
    result['psc']=''
if 'Telefon: ' in spans.keys():
    result['telefon']=spans['Telefon: ']
else:
    result['telefon']=''

At the top of the file I should have # -*- coding: utf-8 -*-, otherwise it causes an error.

+4
source share
2 answers

I am a Spanish programmer and we have some problems with some special characters. The most awesome thing for me in python is to use:

Python: Unicode

:

myString = u'Čečensko'  # Check the u before the string

, , u , .

, , !

:

result={}
if u'Ulice: ' in spans.keys():
    result[u'ulica']=spans[u'Ulice: ']
else:
    result[u'ulica']=''
if u'Kontaktní osoba: ' in spans.keys():
    result[u'kontaktna osoba']=spans[u'Kontaktní osoba: ']
else:
    result[u'kontaktna osoba']=''
if u'Město: ' in spans.keys():
    result[u'mesto']=spans[u'Město: ']
else:
    result[u'mesto']=''
if u'PSČ: ' in spans.keys():
    result[u'psc']=spans[u'PSČ: ']
else:
    result[u'psc']=''
if u'Telefon: ' in spans.keys():
    result[u'telefon']=spans[u'Telefon: ']
else:
    result[u'telefon']=''

unicode , , , Unicode, , .

+3

python - , , , :

, , , :

if isinstance(key, str):
    return key.encode('utf-8')
return key

, :

class SDict(dict):
    @staticmethod
    def prepare_key(key):
        if isinstance(key, str):
            return key.encode('utf-8')
        return key

    def __contains__(self, key):
        return super().__contains__(self.prepare_key(key))

    def __getitem__(self, key):
        return super().__getitem__(self.prepare_key(key))

    def __setitem__(self, key, value):
        return super().__getitem__(self.prepare_key(key), value)

    def __delitem__(self, key):
        return super().__delitem__(self.prepare_key(key))

dict:

>>> d1 = {b'a': 1, b'b': 2}
>>> d2 = SDict(d1)
>>> d2
{b'a': 1, b'b': 2}

in :

>>> 'a' in d1
False
>>> 'a' in d2
True
>>> 'c' in d2
False
>>> 'c' in d1
False

proplerly:

>>> d1['a']
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
KeyError: 'a'
>>> d1[b'a']
1
>>> d2[b'a']
1
>>> d2['a']
1
+1

All Articles