2024-09-26 15:42:47 发布
网友
我想用python中的正则表达式删除重复项,但我有点挣扎
text= 'H. Gerhardstraat 77 1502 CC 77 1502 CC Zaandam' text = re.sub(r'\b(\d{,4})\s(\d{4})\s([A-Za-z]){2}\b', r'\1', text) print(text)
我想要“H.Gerhardstraat 77 1502 CC Zaandam”
我现在明白了: “H.Gerhardstraat 77 Zaandam”
试试这个:
import re c = re.compile(r'([\w\.]+)(?!.*\1)') text = 'H. Gerhardstraat 77 1502 CC 77 1502 CC Zaandam' print(' '.join(c.findall(text)))
输出:
H. Gerhardstraat 77 1502 CC Zaandam
Link to Demo
解释:只有在以后使用否定前瞻断言没有任何相同的单词时,我们才将每个单词(包括句点)与[\w\.]+匹配\1这里指向([\w\.]+)组
[\w\.]+
\1
([\w\.]+)
这样我们只得到列表中最后出现的单词
使用re.sub(pattern, repl, string, count=0, flags=0)的第四个参数count,如下所示:
re.sub(pattern, repl, string, count=0, flags=0)
count
text= 'H. Gerhardstraat 77 1502 CC 77 1502 CC Zaandam' pattern = r'(\d{0,4}\s\d{4}\s[A-Za-z]{2}\s+)' count = len(re.findall(pattern, text)) if count > 1: text = re.sub(pattern, '', text, count -1)
试试这个:
输出:
Link to Demo
解释:只有在以后使用否定前瞻断言没有任何相同的单词时,我们才将每个单词(包括句点)与
[\w\.]+
匹配\1
这里指向([\w\.]+)
组这样我们只得到列表中最后出现的单词
使用
re.sub(pattern, repl, string, count=0, flags=0)
的第四个参数count
,如下所示:相关问题 更多 >
编程相关推荐