2

假设我有以下字符串:

"I am the most foo h4ck3r ever!!"

我正在尝试编写一个 makeSpecial(foo) 函数,其中 foo 子字符串将被包装在一个新的 span 元素中,从而导致:

"I am the most <span class="special">foo></span> h4ck3r ever!!"

BeautifulSoup 似乎是要走的路,但我无法让它发挥作用。

我也可以将它传递给浏览器并使用 javascript 来完成,但这似乎不是一个好主意。

对此的一些建议将非常有用,尤其是在 python 中。

4

3 回答 3

3

这个怎么样:

Python 2.5.1 (r251:54863, Apr 18 2007, 08:51:08) [MSC v.1310 32 bit (Intel)] on
win32
Type "help", "copyright", "credits" or "license" for more information.
>>> def makeSpecial(mystring, special_substr):
...     return mystring.replace(special_substr, '<span class="special">%s</span>
' % special_substr)
...
>>> makeSpecial("I am the most foo h4ck3r ever!!", "foo")
'I am the most <span class="special">foo</span> h4ck3r ever!!'
>>>
于 2008-09-24T02:46:54.350 回答
1

据我所知,你正在做一个简单的字符串替换。您将“foo”替换为“bar foo bar”。所以从字符串你可以使用

replace(old, new[, count])   

返回字符串的副本,其中所有出现的子字符串 old 都替换为 new。如果给定了可选参数 count,则仅替换第一个 count 出现。

所以对你来说,这将是:

myStr.replace("foo", "<span>foo</span>")   
于 2008-09-24T02:49:13.440 回答
0

如果你想用 javascript/jQuery 来做,看看这个问题:Highlight a word with jQuery

于 2008-09-24T02:51:15.027 回答