我正在用Python中的正则表达式处理以下数据
Random
0 helloooo
1 hahaha
2 kebab
3 shsh
4 title
5 miss
6 were
7 laptop
8 welcome
9 pencil
我想删除具有重复字母模式的单词(如blaaaa)、重复字母对(如hahaha)以及在一个字母周围具有相同相邻字母的任何单词(如title、kebab、were)
代码如下:
import pandas as pd
data = {'Random' : ['helloooo', 'hahaha', 'kebab', 'shsh', 'title', 'miss', 'were', 'laptop', 'welcome', 'pencil']}
df = pd.DataFrame(data)
df = df.loc[~df.agg(lambda x: x.str.contains(r"([a-z])+\1{1,}\b"), axis=1).any(1)].reset_index(drop=True)
print(df)
以下是以上的输出,并显示一条警告消息:
UserWarning: This pattern has match groups. To actually get the groups, use str.extract.
Random
0 hahaha
1 kebab
2 shsh
3 title
4 were
5 laptop
6 welcome
7 pencil
然而,我希望看到:
Random
0 laptop
1 welcome
2 pencil
您可以直接使用
Series.str.contains
创建一个掩码,并在以下操作之前禁用用户警告,之后启用用户警告:输出:
您的正则表达式包含一个问题:量词被放在组之外,并且
\1
正在寻找错误的重复字符串。而且,\b
字边界是超边界。([a-z]+)[a-z]?\1
模式匹配一个或多个字母,然后匹配任意一个可选字母,以及紧跟其后的相同子字符串见regex demo
我们可以安全地禁用用户警告,因为我们在这里故意使用捕获组,因为我们需要在这个正则表达式模式中使用反向引用。该警告需要重新启用,以避免在代码的其他部分中使用不必要的捕获组
IIUC,您可以使用类似于
r'(\w+)(\w)?\1'
的模式,即一个或多个字母、可选字母和第一个匹配的字母。这将产生正确的结果:相关问题 更多 >
编程相关推荐