【问题标题】:How to check that the two consecutive words have the same regex pattern如何检查两个连续单词是否具有相同的正则表达式模式
【发布时间】:2013-05-10 11:51:02
【问题描述】:

我已经尝试了几个小时,但我无法达到我的目标。

这是字符串:'Hello world, By The Way stackoverflow is cool place'。 我正在寻找的是匹配两个具有相同正则表达式模式的连续单词。

例如我想用字符串"xx"替换连续且以大写字母开头的单词。

所以当我将它应用到我的字符串时,结果应该是:

Hello world,xx xx xx stackoverflow is cool place

这是我的 sn-p:

myString='Hello world,By The Way stackoverflow is cool place'
re.sub(r"[A-Z]\w+","xx",myString)

但我得到的是: 'xx world,xx xx xx stackoverflow is cool place'

【问题讨论】:

  • 我想到了这个:([A-Z]\S*)(?=\s+[A-Z]) 它几乎可以工作,只是它不匹配链中的最后一个单词。也许其他人会看到一个简单的解决方法?

标签: python regex


【解决方案1】:

使用regex 模块:

>>> import regex
>>> text = 'Hello world,By The Way stackoverflow is cool place'
>>> regex.sub(r'\b[A-Z]\w+(?=\s+[A-Z]\w+)|(?<=\b[A-Z]\w+\s+)[A-Z]\w+', 'xx', text)
'Hello world,xx xx xx stackoverflow is cool place'

【讨论】:

  • 这是我试图做的,但我被正则表达式不支持的积极后向甩掉了,+1
  • 这并不能保证单词以大写字母开头。
  • 为什么你使用 regex 模块而不是 re ?我已经尝试安装它,但弹出了很多问题
  • @EngHamoud Python 的默认 re 不支持变量lookbehinds...无论如何regex 可能成为python 3.4 的一部分
【解决方案2】:

你可以这样做,有以下导入/分配

import re,string

lowercase = string.ascii_lowercase
uppercase = string.ascii_uppercase
punctuation = string.punctuation
digits = string.digits
specials = r'.^+*$\[]|()'

然后有一个函数创建由句子的单词/片段表示的模式

def getPat(text):
    pattern = r""
    for c in text:
        if c in uppercase:
            pattern += '[A-Z]'
        elif c in lowercase:
            pattern += '[a-z]'
        elif c in digits:
            pattern += '\d'
        else:
            if c in specials:
                pattern += '\%s' % c
            else:
                pattern += c
    return pattern

然后你可以检查单词并检查它们的模式是否匹配

sentance = 'Hello world, By Hi nI The Way stackoverflow is cool place'.split()
for word,wordNext in zip(sentance,sentance[1:]):
    if getPat(word) == getPat(wordNext):
        print("{0} = {1}".format(word,wordNext))

会产生

>>> 
By = Hi
The = Way

您可以像这样调整循环来进行替换:

res = ""
for word,wordNext in zip(sentance,sentance[1:]):
    if getPat(word) == getPat(wordNext):
        print("{0} = {1}".format(word,wordNext))
        res += " xx"*2
    else:
        res += " %s" % word
print(res)

愿意:

 Hello world, xx xx Hi nI xx xx Way stackoverflow is cool

【讨论】:

    猜你喜欢
    • 2014-07-30
    • 1970-01-01
    • 2015-10-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多