假设我有一个字符串,其中包含:
'''
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"....}
我可以替换上面dict中的单词,但如果每个键有多个单词,我该怎么做呢?
这是我到目前为止所做的:
stringh=sentence.lower()
for i,j in rep.items():
stringh = stringh.replace(j, i)
print stringh
答案 0 :(得分:1)
遍历列表
stringh=sentence.lower()
for i,j in rep.items():
for k in j:
stringh = stringh.replace(k, i)
print stringh