【问题标题】:How to replace a period with a whitespace but not all whitespaces?如何用空格而不是所有空格替换句点?
【发布时间】:2019-06-27 18:29:20
【问题描述】:

如何将某些句点替换为空格而不是所有句点?

例如:

this_string = 'Man is weak.So they die'
that_string = 'I have a Ph.d'

这里我想要这样的结果:

this_string = 'Man is weak So they die'
some_string = 'I have a Phd'

我希望像 Ph.d 这样的标题保留为一个单词,而将连接 2 个句子的句点替换为空格。


这是我目前所拥有的:

re.sub('[^A-Za-z0-9\s]+',' ', this_string)

这会将所有句点替换为空格。

知道如何改进吗?

【问题讨论】:

  • “某些句点”的规则是什么,在你的例子中只有小写字母之间的句点被替换,这是规则吗?
  • 这有点难,因为它要求你的程序识别单词的含义。
  • 没有确切的规则。它可以在小写或大写之间。所以Ph.D或Ph.d.
  • 我认为你最好尝试搜索和替换特定的已知短语(例如Ph.D不区分大小写)而不是尝试告诉计算机找到weak.So和@987654326之间的区别@

标签: python regex string


【解决方案1】:

您可以使用两个正则表达式作为规则来更改文本:

import re

text = 'Man is weak.So they die. I have a Ph.d.'

text = re.sub(r'([A-Za-z ]{1})(\.)([A-Z]{1})', r'\g<1>. \g<3>', text)  # remove the dot in r'\g<1>. \g<3>' to get '...weak So...'
print(text)  # Man is weak. So they die. I have a Ph.d.

text = re.sub(r'([A-Za-z ]{1})(\.)([a-z]{1})', r'\g<1>\g<3>', text)
print(text)  # Man is weak. So they die. I have a Phd.

最后它并不健壮,因为它是基于规则的转换。像Ph.D 这样的东西是行不通的。

【讨论】:

    【解决方案2】:

    您可以先用一个新符号替换所有有问题的点,然后再用这个符号分割:

    import re
    
    abbreviations = ["Dr.", "Mrs.", "Mr.", "Ph.d"]
    rx = re.compile(r'''(?:{})|((?<=[a-z])\.(?=\s*[A-Z]))'''.format("|".join(abbreviations)))
    
    data = "Man is weak.So they die. I have a Ph.d"
    
    # substitute them first
    def repl(match):
        if match.group(1) is not None:
            return "#!#"
        return match.group(0)
    
    data = rx.sub(repl, data)
    for sent in re.split(r"#!#\s*", data):
        print(sent.replace(".", ""))
    

    这会产生

    Man is weak
    So they die
    I have a Phd
    

    a demo on ideone.com

    【讨论】:

      猜你喜欢
      • 2012-12-16
      • 2018-04-15
      • 1970-01-01
      • 2015-03-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-05-04
      • 1970-01-01
      相关资源
      最近更新 更多