如何将以下规则添加到"如何在字母数字字符和非字母数字字符之间添加空格?"

时间:2018-01-21 21:27:44

标签: regex python-3.x

How to add a space between alphanumeric and non alphanumeric characters?

如何在同一问题中添加以下规则?

  • 如果令牌以"""结束? (撇号,然后是这封信 s),然后将令牌分成两个令牌:前面的部分 撇号和令牌"""
  • 如果令牌以" n&#t; t"结尾? (n-撇号-t),然后将令牌分成两个令牌:" n"之前的部分,以及令牌"不是"
  • 如果令牌以"' m"结尾? (撇号-m),然后将令牌分成两个令牌:撇号前面的部分和令牌" am"
  • 如果上述子规则均不适用,则按原样接受令牌。

以下是我的尝试:

def replacer(match):
    if match.group(1).endswith("'s"):
        return '{} '.format(match.group(1) + "'s")
    elif match.group(2).endswith("n't"):
        return '{} '.format(match.group(2) + "not")
    elif match.group(3).endswith("'m"):
        return '{} '.format(match.group(3) + "'m")
    else:
        return '{}'.format(match.group(4))
rx = re.compile(r'("\'s" | "n\'t" | "\'m")+$')

string = " ".join([rx.sub(replacer, word) for word in string.split()])
print(string)

1 个答案:

答案 0 :(得分:1)

结合其他答案:

import re

string1 = "John's boat hasn't any comfort. I'm pretty sure he'll sell it soon."
string2 = """John had a meeting with 3managers! %nervous:( t^ria7 #manager's."""

def replacer(item):
    if item.endswith("'s"):
        return (item[:-2],) + ("'s",)
    elif item.endswith("n't"):
        return (item[:-3],) + ("not",)
    elif item.endswith("'m"):
        return (item[:-2],) + ("am",)
    else:
        rx = re.compile(r'^(?P<nonword1>\W+)(?P<word1>.*)$|(?P<word2>.*)(?P<nonword2>\W+)$')
        match = rx.search(item)
        if match is None:
            return (item,)

        if match.group('nonword1') is not None:
            return ('{} '.format(match.group('nonword1')), match.group('word1'),)
        else:
            return (match.group('word2'), ' {}'.format(match.group('nonword2')),)

""" tests """
parts = [token for item in string1.split() for token in replacer(item)]
new_string = " ".join(parts)
print(new_string)

parts = [token for item in string2.split() for token in replacer(item)]
new_string = " ".join(parts)
print(new_string)

这会产生

John 's boat has not any comfort  . I am pretty sure he'll sell it soon  .
John had a meeting with 3managers  ! %  nervous:( t^ria7 #  manager's.