【问题标题】:Extract all strings between delimiters提取分隔符之间的所有字符串
【发布时间】:2018-10-13 11:55:49
【问题描述】:

我编写了一个函数来提取两个分隔符之间的字符串。但是在某些文件中,这些分隔符出现了好几次,所以我想把它们全部提取出来。 在我的实际功能中,它只提取它遇到的第一个然后退出。

我该如何解决?

def extraction_error_CF(file): 

    f=open(file,'r')
    file=f.read()
    f.close()
    start = file.find('Error validating') #1st delimiter
    end = file.find('</SPAN><BR>', start) # 2nd delimiter
    if start!=-1 and end!=-1:             #If these two delimiters are present...
        return(file[start:end])
    else:
        return""

【问题讨论】:

  • 为此使用适当的 html/xml 解析器
  • 你可以给find传递一个额外的参数,这是最后找到的模式的偏移量,只需加1你就会找到所有的
  • 抱歉,我刚开始编写代码,我不理解您使用 html/xml 解析器的解决方案,第二个解决方案我将“1”添加到:file.find('Error validating' ,1) 但它仍然只找到第一个。谢谢
  • @Jean-FrançoisFabre 我们不能盲目地假设文件的内容实际上是一个完整的 HTML 文档——因为我们知道它也可以是一个日志文件,在某些消息中带有标记或其他任何包含标记的内容一个真正的 HTML 文档。
  • @Tom92 如果没有您文件内容的代表性样本,我们将无法正确回答您的问题。

标签: python file find extract


【解决方案1】:

对于 HTML/XML,您应该完全使用强大的模块,例如 BeautifulSoup, 但是如果你真的只想要两个分隔符之间的内容,你可以使用相同的函数,但是将结果添加到列表中(例如)然后你可以打印出来

def extraction_error_CF(file): 

    f=open(file,'r')
    file=f.read()
    f.close()

    # Patterns
    first = "Error validating"
    second = "</span><br>"

    # For all the matches
    results = []

    # Iterate the whole file
    start = file.find(first)
    end = file.find(second)
    while start != -1 and end != -1:
        # Add everything between the patterns
        # but not including the patterns
        results.append(file[start+len(first):end])
        # Removing the text that already passed
        file = file[end+len(second):]

        start = file.find(first)
        end = file.find(second)

    # Return the content of the list as a string
    if len(results) != 0:
        return "".join(r for r in results)
    else:
        return None

print(extraction_error_CF("test"))

【讨论】:

    【解决方案2】:
    import re
    
    def extraction_error_CF(file): # Get error from CF upload 
        f=open(file,'r')
        file=f.read()
        f.close()
        start = re.findall('Error validating(.*)</SPAN><BR>',file)
        if start != -1:
            return start
        else:
            return""
    

    这就是我所做的,它运作良好,谢谢大家!

    【讨论】:

      猜你喜欢
      • 2015-08-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-08-18
      • 1970-01-01
      • 2021-04-04
      • 2016-02-10
      • 2016-09-05
      相关资源
      最近更新 更多