【问题标题】:Deleting patterned text from an html using python使用python从html中删除带图案的文本
【发布时间】:2017-02-22 11:09:53
【问题描述】:

我尝试使用python编写脚本,删除html中的某个模式文本。但是,我的代码似乎不起作用..您能帮我检查一下哪里出错了吗?

import os, re

cwd = os.getcwd()
print ('Now you are at this directory: \n' + cwd)

# find files that have an extension with HTML
Files = os.listdir(cwd)
print Files

def func(file):
    for file in os.listdir(cwd):
        if file.endswith('.html'):
            for line in open(file):
                re.sub(r'<strong>.*?<\/strong>', '', line)
                # I feel the above line has some problems
func(file)

非常感谢您!

【问题讨论】:

    标签: python html regex


    【解决方案1】:

    你不必在你的 re. \/其实只是一个普通的/。完整参考见the re documentation的介绍。

    你的正则表达式应该是:r'&lt;strong&gt;.*?&lt;/strong&gt;'

    但不建议使用正则表达式解析 html。请参阅BeautifulSoup

    line = '<p>some text, <strong>SOME STRONG TEXT </strong> and again <strong>STONG TEXT</strong></p>'
    re.sub(r'<strong>.*?<\/strong>', '', line)
    #'<p>some text,  and again </p>'
    

    【讨论】:

    • 谢谢蒂埃里,我一定会去看看beautifulsoup!对于正则表达式,我尝试了两种模式,但它们都不起作用……如果您使用我的原始脚本并尝试打印出匹配的文本,它们实际上是正确的。我只是不确定代码中的哪个部分有误,导致我无法替换匹配的字符串...
    【解决方案2】:

    希望这会有所帮助!

    import os, re
    
    cwd = os.getcwd()
    print ('Now you are at this directory: \n' + cwd)
    
    # find files that have an extension with HTML
    Files = os.listdir(cwd)
    
    def func(file):
        for file in os.listdir(cwd):
            if file.endswith('.html'):
                    f = open(file, "r+")
                    text  = re.sub(r'\<strong\>.*\<\/strong\>',"",f.read())
                    f.close()
                    f = open(file, "w")
                    f.write(text)
                    f.close()
    func(file)
    

    【讨论】:

    • 谢谢你成功了!!就我而言,我可能需要进一步尝试——看看漂亮的汤是否会更有帮助。 :)
    猜你喜欢
    • 2010-12-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-11-27
    • 1970-01-01
    相关资源
    最近更新 更多