【问题标题】:Delete words with regex patterns in Python from a dataframe从数据框中删除具有 Python 中正则表达式模式的单词
【发布时间】:2021-11-04 10:14:38
【问题描述】:

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

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

我想删除具有重复字母模式的单词(例如 blaaaa)、重复的一对字母(例如 haha​​ha)以及一个字母周围具有相同相邻字母的任何单词(例如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

【问题讨论】:

    标签: python regex pandas dataframe


    【解决方案1】:

    IIUC,你可以使用类似r'(\w+)(\w)?\1' 的模式,即一个或多个字母,一个可选字母,以及第一个匹配的字母。这给出了正确的结果:

    df[~df.Random.str.contains(r'(\w+)(\w)?\1')]
    

    【讨论】:

      【解决方案2】:

      您可以直接使用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 模式匹配一​​个或多个字母,然后是任意一个可选字母,以及紧随其后的相同子字符串。

      请参阅regex demo

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

      【讨论】:

      • 感谢您的解释!我收到警告错误 --> NameError: name 'warnings' is not defined
      • @user01 抱歉,复制/粘贴时丢失。已添加import warnings
      • 另外,如果我想检查重复的数字。在哪里添加 '\d+' 到正则表达式?
      • @user01 ([a-z\d]+)[a-z\d]?\1? (\w+)\w?\1? ([^\W_]+)[^\W_]?\1?你能准确地说出你想要匹配的字符吗?如果有的话,那么(.+).?\1?
      • @user01 然后使用([a-z2-5]+)[a-z2-5]?\1
      猜你喜欢
      • 2023-03-05
      • 1970-01-01
      • 2022-01-13
      • 1970-01-01
      • 1970-01-01
      • 2019-11-10
      • 1970-01-01
      • 2014-05-20
      • 1970-01-01
      相关资源
      最近更新 更多