2012-12-09 60 views
0

我正在使用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    
+3

一個例子,那豈不是更好地使用標準Python字符串格式化功能? 「{0},{1},{2},{3}'。格式(* word)'將獲得相同的結果。 –

+2

您將以這種方式將1000變成1foo。 –

+1

爲什麼你接受[我的回答](http://stackoverflow.com/a/13784019/722121)到[你的最後一個問題](http://stackoverflow.com/q/13784006/722121),然後繼續使用破解的版本?此外,通過使用[字符串格式化語法](http://docs.python.org/3/library/string.html#formatstrings)並使用'str.format()',您可以讓自己變得更輕鬆。 –

回答

1

類似的東西要好得多寫成(用於非HTML):

>>> text = '000 this is 001 some 002 text 003' 
>>> word = ['foo', 'bar', 'that', 'these'] 
>>> word_list = iter(word) 
>>> import re 
>>> re.sub(r'\d+', lambda L: next(word_list), text) 
'foo this is bar some that text these' 
+0

在文本中也有類似'291px'的東西,所以這是行不通的。 – BrtH

+0

@BrtH非常好 - 指的是原始的非HTML文本的東西 –

+1

確實。 btw,對於非html文本,'re.sub(r'\ d +',lambda m:word [int(m.group(0))],text)'會更簡單。 – BrtH

0

不幸的是,你的做法是完全錯誤的,這樣的問題,因爲他們是很好的人選Template Engines

可以與現有的模板引擎的數量實驗或者我可以建議Jinja2這將有助於你的目的 這裏是Jinja2

>>> text = """ 
{% for style in styles %} 
<p><span class="newStyle{{ style.styleno }}" 
{% for orin in style.orin %} 
style="{{ orin.orin }}: {{ orin.attrib }}px 
{% endfor %} 
">{{ style.val }}</span></p> 
{% endfor %} 
""" 
>>> styles = [{'no':1, 
      "orin":[{"orin":"left", "attrib":291}, 
       {"orin":"top", "attrib":258}], 
      "val":"000"}, 
      {'no':2, 
     "orin":[{"orin":"left", "attrib":100}, 
      {"orin":"top", "attrib":222}, 
      {"orin":"height", "attrib":222}, 
      {"orin":"width", "attrib":222}], 
     "val":"001"}] 
>>> template = Template(text) 
>>> template.render(styles = styles) 
u'\n\n<p><span class="newStyle"\n\nstyle="left: 291px\n\nstyle="top: 258px\n\n">000</span></p>\n\n<p><span class="newStyle"\n\nstyle="left: 100px\n\nstyle="top: 222px\n\nstyle="height: 222px\n\nstyle="width: 222px\n\n">001</span></p>\n' 
>>> 
相關問題