2014-09-01 84 views
0

假设我有一个字符串,其内容为:如何在多个类别中搜索和替换python中的关键字?

''' 
Looking closely we find Pepsi and Coca-cola have been the two two biggest brands of soda in the world for the past four years. 
''' 

,我想表示词映射到其类别为:

classes={"NAME":["pepsi","coca-cola", "james","jill"...],"CATEGORY":["soda","food","automobile"....],"NUMBER":["one","two","three","four"....]} 

所以,在最后我想有原始字符串:

Looking closely we find NAME and NAME have been the two biggest brands of CATEGORY in the world for the past NUMBER years 

一个简单的字典,如:

rep = {"NAME": "pepsi", "CATEGORY": "soda"....} 

我可以替换上述词典中的词,但如果每个键有多个词,我该怎么办?

这是我到目前为止有:

stringh=sentence.lower() 

for i,j in rep.items(): 
    stringh = stringh.replace(j, i) 

print stringh 

回答

1

通过列表

stringh=sentence.lower() 

for i,j in rep.items(): 
    for k in j: 
     stringh = stringh.replace(k, i) 

print stringh 
迭代