如何检查两个连续的单词是否具有相同的正则表达式模式。

3
我尝试了好几个小时,但我没有达成目标。
以下是字符串:'Hello world, By The Way stackoverflow is cool place'。 我想要的是匹配两个连续的单词并且这两个单词具有相同的正则表达式模式。
例如,我想要用字符串"xx"替换以大写字母开头且相邻的单词。
因此,当我将其应用于我的字符串时,结果应该是: Hello world,xx xx xx stackoverflow is cool place 以下是我的代码片段:
myString='Hello world,By The Way stackoverflow is cool place'
re.sub(r"[A-Z]\w+","xx",myString)

但我得到的信息是: 'xx世界,xx xx xx StackOverflow是一个很酷的地方'

我想到了这个正则表达式:([A-Z]\S*)(?=\s+[A-Z]) 它几乎可以工作,但是它无法匹配链中的最后一个单词。也许其他人会看到一个简单的解决方法? - Patashu
2个回答

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'

这就是我想要制作的东西,但是由于regexpal不支持正向后瞻,所以我被扰乱了,+1。 - Patashu
这并不保证单词以大写字母开头。 - nhahtdh
为什么你使用了 regex 模块而不是 re?我尝试安装它,但出现了很多问题。 - Hamoudaq
@EngHamoud Python的默认re不支持变量lookbehinds... 无论如何,regex可能会成为Python3.4的一部分。 - jamylak

0
你可以这样做,使用以下导入/赋值:
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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接