Python - replace word with another [closed]

2019-03-06 19:43发布

问题:

I have html table with 12 cells. Each cell has a word to be replaced. All of the words are identical. Also I have a list with 12 elements. Each element is a word. I need to replace each word with the appropriate word from the list. First word to be replaced with the first element, second with the second element and so on. Can you give me an example how to do this, I'm new at python?

回答1:

words = ['fist','second','thrid']

for word in words:
    yourText = yourText.replace('theOldWord',word,1)


回答2:

For the first problem, use the replace method.

word = "your_word"
new_word = "new_word"
html_text.replace(word, new_word)

Also I have a list with 12 elements. Each element is a word. I need to replace each word with the appropriate word from the list.

Create a dictionary mapping "old word" to "new word"

>>> list = ["oldword0", "oldword1"]
>>> mapping = {"oldword0": "newword0", "oldword1": "newword1"}
>>> map(lambda x: mapping[x], list)
['newword0', 'newword1']