【问题标题】:BeautifulSoup. Find and replace all instances of a word with one from my list美丽汤。从我的列表中查找并替换一个单词的所有实例
【发布时间】:2013-07-25 16:50:39
【问题描述】:

我有一本字典。关键是动物。该值是不同动物的列表。 列表的大小和动物是什么将随着每个应用程序的使用而改变。 对于列表中的每只动物,我想在我的 BeautifulSoup 树中搜索,找到该动物的所有出现并将其包装在一个跨度标记中/用我的跨度标记的动物替换它

我无法将变量传递给 re.compile() 以帮助搜索这些动物。

我也想知道如果附近没有标签,你能否替换 BeautifulSoup 中字符串中的单个单词。

Windows 7、Python 2.7、BeautifulSoup 4 代码是这样的

for key, value in animals.iteritems():      #go through dict
    if key == 'ANIMALS':                    
        for name in value:                  #for name of animals in list
            animal_tag = soup.new_tag("span", id=key)   #create new tag with id=ANIMALS
            animal_tag.string = name                    #create new string with name of animal
            name = soup.find(text=re.compile(r'^%s$' % name)) 
            #find animals in doc - keeps throwing a none type error
            #replace animal in doc with new <span id="ANIMALS">animal>/span>  

感谢任何人提供的任何帮助。

【问题讨论】:

    标签: python list variables beautifulsoup


    【解决方案1】:

    在这种情况下,我认为使用string.replace() 操作原始 HTML 会更简单。如果text 等于原始 HTML:

    for key, value in animals.iteritems():
        if key == 'ANIMALS':                    
            for name in value:
                text.replace(name,"<span id="+key+">"+name+"</span>")
    

    【讨论】:

    • tehsockz,感谢您的快速回复。虽然这似乎对我不起作用,但它开启了以不同方式解决问题的想法,这总是有帮助的。我很感激这个答案。试图投票但缺乏所需的声誉。
    • 从头开始。这是工作。只是我的程序的逻辑需要工作。
    猜你喜欢
    • 1970-01-01
    • 2020-12-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多