我正在使用Python創建一個詞彙雲程序,並且我陷入了一個單詞替換函數。我試圖用一個有序列表中的單詞替換html文件中的一組數字(所以我正在處理一個字符串)。因此,000將與列表中的第一個字,001與第二等來代替使用Python替換列表中項目的字詞
通過相對簡單的字符串移動時,下面這種方法的工作原理:
def textReplace():
text = '000 this is 001 some 002 text 003 '
word = ['foo', 'bar', 'that', 'these']
for a in word:
for y, w in enumerate(text):
x = "00"+str(y)
text = text.replace(x, a)
print text
我通過工作我的方式html文件(我將文件的一部分放在下面的字符串中),而不是用列表中的連續項替換每個000,001,002等實例,而是用第一項代替所有數字。爲什麼此方法在上面的字符串上工作,但不在下面的字符串中。任何幫助表示讚賞。謝謝!
def htmlReplace():
text = '<p><span class="newStyle0" style="left: 291px; top: 258px">000</span></p> <p><span class="newStyle1" style="left: 85px; top: 200px">001</span></p> <p><span class="newStyle2" style="left: 580px; top: 400px; width: 167px; height: 97px">002</span></p> <p><span class="newStyle3" style="left: 375px; top: 165px">003</span></p>'
word = ['foo', 'bar', 'that', 'these']
for a in word:
for y, w in enumerate(text):
x = "00"+str(y)
text = text.replace(x, a)
print text
一個例子,那豈不是更好地使用標準Python字符串格式化功能? 「{0},{1},{2},{3}'。格式(* word)'將獲得相同的結果。 –
您將以這種方式將1000變成1foo。 –
爲什麼你接受[我的回答](http://stackoverflow.com/a/13784019/722121)到[你的最後一個問題](http://stackoverflow.com/q/13784006/722121),然後繼續使用破解的版本?此外,通過使用[字符串格式化語法](http://docs.python.org/3/library/string.html#formatstrings)並使用'str.format()',您可以讓自己變得更輕鬆。 –