The substitution of many different words in a sentence can be achieved by matching each word in the sentence to the dictionary in turn, and matching the successful replacement, but this method intuitively takes a long time, and for a long document, it can take a lot of Here is a way to replace many different words in a sentence at once, the code is as follows:
#!/usr/bin/env python#Coding=utf-8ImportRedefmultiple_replace (text, idict): Rx= Re.compile ('|'. Join (Map (Re.escape, idict )))defOne_xlat (Match):returnidict[match.group (0)]returnrx.sub (One_xlat, text) idict={'3':'2','Apples':'Peaches'} textbefore='I bought 3 pears and 4 apples'Textafter=multiple_replace (textbefore,idict)Print(Textbefore)Print(Textafter)
The result of the operation is:
I bought 3 pears and 4 Applesi bought 2 pears and 4 peaches
As can be seen, the return value of the Multiple_replace () function is also a string (sentence), replacing "3" with "2" at once, substituting "apples" with "Peaches"
Reference: http://blog.csdn.net/huludan/article/details/50925735
Replace several different words in a sentence--python implementation