【问题标题】:How to get rid of lines surrounded by empty spaces?如何摆脱被空白空间包围的线条?
【发布时间】:2020-09-29 20:49:01
【问题描述】:

我的文本看起来像这样:

text
text
text


to remove

text
text
text


to remove
 

text
text
text

有不间断的文本块,我需要删除上面示例中看起来像“要删除”的行,它们上面有 2 个空行,下面有 1 个空行。有没有办法以编程方式删除这些行以及 Python 中围绕它们的空格?

【问题讨论】:

  • 总是这种格式吗? (2 个空行,一个带文本,一个空行)除了想要的文本?

标签: python text nlp


【解决方案1】:

Regular expressions 是一种强大的模式搜索和替换工具。

假设文本在text变量中,

import re

re.sub('\n{3}[^\n]+\n{2}', '\n', text, re.M)

【讨论】:

    【解决方案2】:

    这应该可行:

    l=[]
    with open('yourfile.txt') as f:
        for i in f:
            l.append(i)
    
    m=set()
    for i in range(len(l)):
        if l[i].replace(' ', '')=='\n':
            m.add(i)
    for i in range(1, len(l)-1):
        if l[i-1].replace(' ', '')=='\n' and l[i+1].replace(' ', '')=='\n':
            m.add(i)
    
    result=[l[i] for i in range(len(l)) if i not in m]
    
    with open('yourfile.txt', 'w') as f:
        for i in result:
            f.write(i)
    

    【讨论】:

    • 感谢您的回答!您能否指出如何删除每个空格下方的一行?
    【解决方案3】:

    使用函数 .translate()。 translate() 函数从字符串中删除空格。这是一个教程:https://www.journaldev.com/23763/python-remove-spaces-from-string#:~:text=Python%20String%20strip()%20function%20will%20remove%20leading%20and%20trailing%20whitespaces.&text=If%20you%20want%20to%20remove,or%20rstrip()%20function%20instead。 或

    import string
    s = "Text     Text     Text"
    print(s.translate({ord(c): None for c in string.whitespace}))
    

    它将打印出TextTextText

    这是一个示例:https://repl.it/repls/AwfulAmusedGlitches#main.py

    【讨论】:

      【解决方案4】:

      我认为正则表达式应该可以工作。但是,在这里我想也许这可能是一个展示使用the walrus operator := in python 3.8: 在列表理解中查找多行模式位置的示例的机会。 如果模式更复杂,将来可能会有用。

      text = """
      text
      text
      text
      
      
      to remove
      
      text
      text
      text
      
      
      to remove
       
      
      text
      text
      text
      """
      
      curr = ("", "", "", "")
      
      positions = [
        (i-4, i) 
        for i, line in enumerate(text.split("\n"))
        if (curr := (curr[1], curr[2], curr[3], line.strip())) == ("", "", "to remove", "")
      ]
      

      结果positions 这里是一个元组列表,指示分隔符模式的范围: [(3, 7), (10, 14)]

      是的,已经太复杂了!最后一点,请耐心等待。您可以将范围列表用作any() 的过滤器,以检查行是否不在任何分隔符范围内:

      remained_lines = [
        line
        for pos, line in enumerate(text.split("\n"))
        if not any([i<= pos < j for i, j in positions])
      ]
      new_text = "\n".join(remained_lines)
      

      总之,尽可能使用正则表达式,但是,这里我有一些新的和旧的 Python 特性,对于未来遇到更奇怪分隔符情况的读者可能会派上用场。

      【讨论】:

        【解决方案5】:

        这应该可以解决您的问题:

        text = "text \ntext \ntext \n\n\nto remove \n \n \ntext \ntext"
        text = "".join([s for s in text.strip().splitlines(True) if s.strip()])
        
        print(text)
        

        输出会是这样的:

        text
        text
        text
        to remove
        text
        text
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2016-12-21
          • 2014-08-15
          • 1970-01-01
          • 2014-08-17
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多