【问题标题】:How to remove only certain characters with a pre condition given如何在给定的前提条件下仅删除某些字符
【发布时间】:2021-12-09 09:20:54
【问题描述】:

我正在尝试使用 Python 从字符串列表中删除特定字符。

我的字符串是这样的:

<p><a href="first/Fruit-Shop-One.html">Fruit-Shop-One</a></p>
<p><a href="first/Fruit-Shop-Two.html">Fruit-Shop-Two</a></p>

我想要的是在不破坏链接的情况下删除“-”。所以最终的结果一定是这样的:

<p><a href="first/Fruit-Shop-One.html">Fruit Shop One</a></p>
<p><a href="first/Fruit-Shop-Two.html">Fruit Shop Two</a></p>

【问题讨论】:

标签: python string replace


【解决方案1】:

这是一种快速而肮脏的方法,通过拆分字符串并稍后将它们连接在一起。

strings = ['<p><a href="first/Fruit-Shop-One.html">Fruit-Shop-One</a></p>', '<p><a href="first/Fruit-Shop-Two.html">Fruit-Shop-Two</a></p>']
for string in strings:
    new_string = string.split('">')[0] + '">' + string.split('">')[1].replace("-", " ")

输出:

<p><a href="first/Fruit-Shop-One.html">Fruit Shop One</a></p>
<p><a href="first/Fruit-Shop-Two.html">Fruit Shop Two</a></p>

或者在列表理解中

new_strings = [string.split('">')[0] + '">' + string.split('">')[1].replace("-", " ") for string in strings]

输出:

['<p><a href="first/Fruit-Shop-One.html">Fruit Shop One</a></p>', '<p><a href="first/Fruit-Shop-Two.html">Fruit Shop Two</a></p>']

【讨论】:

    【解决方案2】:
    from bs4 import BeautifulSoup
    
    string_one = '<p><a href="first/Fruit-Shop-One.html">Fruit-Shop-One</a></p>'
    
    soup = BeautifulSoup(string_one, "html.parser")
    
    for a in soup.findAll('a'):
        a.string = a.string.replace('-', ' ')
    
    
    new_string = str(soup)
    
    print(soup)
    # <p><a href="first/Fruit-Shop-One.html">Fruit Shop One</a></p>
    

    【讨论】:

    • 这应该适用于一大串 html 中的所有“a href”链接。
    猜你喜欢
    • 1970-01-01
    • 2022-12-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-12
    相关资源
    最近更新 更多