Replacing a word in a list with a value from a dict

后端 未结 2 1858
抹茶落季
抹茶落季 2021-01-15 05:59

I\'m trying to create a simple program that lets you enter a sentence which will then be split into individual words, saved as splitline. For example:



        
2条回答
  •  走了就别回头了
    2021-01-15 06:04

    Now that you have your dict the proper way, you can do regular dict object stuff like checking for keys and grabbing values:

    >>> text = 'the man lives in a house'
    >>> mydict = {"the":1,"in":2,"a":3}
    >>> splitlines = text.split()
    >>> for word in splitlines:
        if word in mydict:
            text = text.replace(word,str(mydict[word]))
    

    HOWEVER, note that with this:

    >>> text
    '1 m3n lives 2 3 house'
    

    since a is a key, the a in man will be replaced. You can instead use regex to ensure word boundaries:

    >>> text = 'the man lives in a house'
    >>> for word in splitlines:
        if word in mydict:
            text = re.sub(r'\b'+word+r'\b',str(mydict[word]),text)
    
    
    >>> text
    '1 man lives 2 3 house'
    

    the \b ensures that there is word boundary around each match.

提交回复
热议问题