简体   繁体   中英

Unexpected output replacing words using dictionary and dic.iteritems - Python

I have this dictionary:

global dicnames

dicnames= {'co':'company' , 'svcs':'services' , 'hlth':'health' , 'equip':'equipment', 'corp':'corporation', 'intl':'international' } 

I created this function to replace certain words in a string by their value in the dictionary:

def reemp(text):

    for i , j in dicnames.iteritems():
        text=text.replace(i,j)
    return text

It's working with all the words except 'corp'. For example:

 reemp('uni corp')

    Out[24]:
    'uni companyrp'

So . What's wrong in my code and How Can I fix that?

Use an OrderedDict so that the replacements occur in the order you expect.

from collections import OrderedDict

dicnames = OrderedDict([
    ('svcs', 'services'),
    ('hlth', 'health'),
    ('equip', 'equipment'),
    ('corp', 'corporation'),
    ('intl', 'international'),
    ('co', 'company'),
])

def reemp(text):
    for i , j in dicnames.iteritems():
        text = text.replace(i,j)
    return text

print(reemp('uni corp'))

But even then you will have problems -- 'co' starts 'company' and 'corporation'. You will get multiple replacements. You need to rework reemp so that it does only a single replacement.

This will do a single replacement for you:

def reemp(text):
    for i , j in dicnames.iteritems():
        if i in text:
            return text.replace(i,j)
    return text

If you combine that with the OrderedDict , you should be able to work it out.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM