【问题标题】:Adding New Element to Text Substring向文本子字符串添加新元素
【发布时间】:2010-09-12 14:40:28
【问题描述】:

假设我有以下字符串:

"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 中。

【问题讨论】:

    标签: javascript jquery python beautifulsoup


    【解决方案1】:

    这个怎么样:

    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!!'
    >>>
    

    【讨论】:

    • 我同意这一点,但根据上下文,一些错误处理可能有用
    【解决方案2】:

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

    replace(old, new[, count])   
    

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

    所以对你来说是:

    myStr.replace("foo", "<span>foo</span>")   
    

    【讨论】:

      【解决方案3】:

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2018-05-15
        • 1970-01-01
        • 1970-01-01
        • 2022-01-08
        • 1970-01-01
        • 2017-06-19
        • 1970-01-01
        • 2020-03-08
        相关资源
        最近更新 更多