从数据帧中删除 Python 中带有正则表达式模式的单词

用户01

我正在使用 Python 中的正则表达式来处理以下数据。

     Random
0  helloooo
1    hahaha
2     kebab
3      shsh
4     title
5      miss
6      were
7    laptop
8   welcome
9    pencil

我想删除具有重复字母模式(例如blaaaa)的话,重复对字母(例如哈哈哈),并且具有围绕一个字母相同的相邻字母的任意单词(例如山雀乐,柯BAB,瓦特ERE)。

这是代码:

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直接使用创建掩码并在之前禁用用户警告并在之后启用它:

import pandas as pd
import warnings

data = {'Random' : ['helloooo', 'hahaha', 'kebab', 'shsh', 'title', 'miss', 'were', 'laptop', 'welcome', 'pencil']}
df = pd.DataFrame(data)
warnings.filterwarnings("ignore", 'This pattern has match groups') # Disable the warning
df['Random'] = df['Random'][~df['Random'].str.contains(r"([a-z]+)[a-z]?\1")]
warnings.filterwarnings("always", 'This pattern has match groups') # Enable the warning

输出:

>>> df['Random'][~df['Random'].str.contains(r"([a-z]+)[a-z]?\1")]
# =>     
7     laptop
8    welcome
9     pencil
Name: Random, dtype: object

您拥有的正则表达式包含一个问题:量词位于组之外,并且\1正在寻找错误的重复字符串。此外,\b词边界是多余的。([a-z]+)[a-z]?\1模式匹配一​​个或多个字母,然后是任意一个可选字母,以及紧跟其后的相同子串。

请参阅正则表达式演示

我们可以安全地禁用用户警告,因为我们在这里故意使用捕获组,因为我们需要在此正则表达式模式中使用反向引用。警告需要重新启用,以避免在我们代码的其他部分不需要使用捕获组。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

正则表达式在Python中具有findall多种模式

Python正则表达式用模式中的可选单词拆分

Python中的正则表达式以匹配带有特殊字符的单词

python中带有re.search的正则表达式不起作用

python中带有正则表达式比较的字符串在python中失败

python中的正则表达式模式匹配

python中的负正则表达式模式匹配

用Python中的正则表达式解析具有重复模式的字符串?

正则表达式模式无法在python中匹配

在Python中替换的正则表达式模式

python PyQT5中带有外来字符的Python正则表达式

Python正则表达式可匹配{}中的所有单词

正则表达式在python中查找特定模式

有关python中单词边界的正则表达式模式

python正则表达式中的整个单词

在Python中重复正则表达式模式

带有urlParse的python中的正则表达式

Python正则表达式,如果所有完整单词都在字符串中

在 Python 中匹配多行正则表达式模式

python正则表达式删除数据帧列中的所有内容,不应该

使用python提取单词中特定符号后的所有单词的正则表达式

python中带有[和*的正则表达式

Python 中逗号分隔单词的正则表达式

Python - 从没有正则表达式的段落中的引号中提取单词

递归正则表达式模式 - 在 python 中

正则表达式删除python中数据的某些模式匹配

正则表达式在python中的开始和结束使用变量中查找带有字母的单词?

Python正则表达式在分组中返回没有双引号的单词

Python 中的正则表达式模式