【问题标题】:Delete based on presence基于存在删除
【发布时间】:2020-10-21 11:02:49
【问题描述】:

我正在尝试分析一篇文章以确定是否出现了特定的子字符串。

如果出现"Bill",那么我想从文章中删除子字符串的父句子,以及第一个删除句子之后的每个句子。

如果"Bill"没有出现,则文章不做任何改动。

示例文本:

stringy = """This is Bill Everest here. A long time ago in, erm, this galaxy, a game called Star Wars Episode I: Racer was a smash hit, leading to dozens of enthusiastic magazine reviews with the byline "now this is podracing!" Unfortunately, the intervening years have been unkind to the Star Wars prequels, Star Fox in the way you can rotate your craft to fit through narrow gaps. 

This is Bill, signing off. Thank you for reading. And see you tomorrow!"""

目标子串为“Bill”时的期望结果:

stringy = """This is Bill Everest here. A long time ago in, erm, this galaxy, a game called Star Wars Episode I: Racer was a smash hit, leading to dozens of enthusiastic magazine reviews with the byline "now this is podracing!" Unfortunately, the intervening years have been unkind to the Star Wars prequels, but does that hindsight extend to this thoroughly literally-named racing tie-in? Star Fox in the way you can rotate your craft to fit through narrow gaps.
"""

这是目前为止的代码:

if "Bill" not in stringy[-200:]:
    print(stringy)

text = stringy.rsplit("Bill")[0]

text = text.split('.')[:-1]

text = '.'.join(text) + '.'

"Bill" 出现在最后 200 个字符之外时,它目前不起作用,在"Bill" 的第一个实例处截断文本(开头句,"This is Bill Everest here")。如何将此代码更改为仅选择最后 200 个字符中的 "Bill"s?

【问题讨论】:

    标签: python python-3.x algorithm substring re


    【解决方案1】:

    这是另一种使用正则表达式遍历每个句子的方法。我们保留行数,一旦我们进入最后 200 个字符,我们就会检查行中的“Bill”。如果找到,我们从该行开始排除。

    希望代码足够可读。

    import re
    
    def remove_bill(stringy):
        sentences = re.findall(r'([A-Z][^\.!?]*[\.!?]\s*\n*)', stringy)
        total = len(stringy)
        count = 0
        for index, line in enumerate(sentences):
            #Check each index of 'Bill' in line
            for pos in (m.start() for m in re.finditer('Bill', line)):
                if count + pos >= total - 200:
                    stringy = ''.join(sentences[:index])
                    return stringy
            count += len(line)
        return stringy
    
    stringy = remove_bill(stringy)
    

    【讨论】:

      【解决方案2】:

      这里是你如何使用re

      import re
      
      stringy = """..."""
      target = "Bill"
      
      l = re.findall(r'([A-Z][^\.!?]*[\.!?])',stringy)
      
      for i in range(len(l)-1,0,-1):
          if target in l[i] and sum([len(a) for a in l[i:]])-sum([len(a) for a in l[i].split(target)[:-1]]) < 200:
              strings = ' '.join(l[:i])
      
      print(stringy)
      

      【讨论】:

      • 非常感谢!但我注意到,如果“Bill”在最后两百个字符中出现两次,它只会删除最右边的实例。如何更改代码以在最后 200 个字符中包含多个“Bill”?
      • 这让事情变得更简单,只需删除break :)
      猜你喜欢
      • 1970-01-01
      • 2019-01-18
      • 2014-07-18
      • 2021-06-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-11-03
      相关资源
      最近更新 更多