'''
有一段英文文本,其中有单词连续重复了 2 次,编写程序检查重复的单词并只保留一个
例: This is a a desk.
输出 This is a desk.
'''
# 方法一
import re
x = 'This is a a desk.'
# 设置字符串
pattern = re.compile(r'(w+)(s+1){1,}')
# 匹配单词和空格间的位置
# w 匹配包括下划线的任何单词字符 [A-Za-z0-9_]
# s 匹配任何空白字符
# {1,} 大于 1 个
matchResult = pattern.search(x)
# 查找这样的结果
x = pattern.sub(matchResult.group(1),x)
# sub 进行替换字符
# group(1) 为 a group(0) 为 a a
print(x)
# This is a desk.
# 方法二
import re
x = 'This is a a desk.'
# 设置字符串
pattern = re.compile(r'(?P<f>w+)s(?P=f)')
# # 匹配单词和空格间的位置
# w 匹配包括下划线的任何单词字符 [A-Za-z0-9_]
matchResult = pattern.search(x)
# 匹配到 a a
x = x.replace(matchResult.group(0),matchResult.group(1))
# 字符串对象.replace(旧字符串,新字符串)
# print(matchResult.group(0))
# a a
# print(matchResult.group(1))
# a
print(x)
# This is a desk.
2020-04-19