我正在用 Python 创建一个词云程序,但我被困在一个词替换功能上。我正在尝试用有序列表中的单词替换 html 文件中的一组数字(所以我正在使用字符串)。因此 000 将替换为列表中的第一个单词,001 将替换为第二个单词,依此类推。
下面的方法在通过相对简单的字符串时有效:
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