你可以这样做,有以下导入/分配
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