首页 > 解决方案 > 使用 Regex Python 删除数据框中字符串中的前 2 个单词和后 2 个单词

问题描述

我在 df 中有一列包含以下字符串:

>>> import pandas as pd
>>> df = pd.DataFrame({'Sentence':['The cat is jumping off the bridge', 'The dog jumped over the brown fox, the bus is coming now', 'The bus is coming']})
>>> df
                            Sentence
0  The cat is jumping off the bridge
1  The dog jumped over the brown fox, the bus is coming now
2  The bus is coming

我想使用正则表达式删除所有字符串的前 2 个单词和最后 2 个单词。一行可以包含多个字符串(row 1)。如果字符串少于 4 个单词,则不应为该字符串返回任何内容(row 2)。输出应如下所示:

>>> df
                            Sentence                               String
0  The cat is jumping off the bridge                          is jumping off
1  The dog jumped over the brown fox, the bus is coming now   jumped over the, is  
2  The bus is coming

我尝试使用此代码只是为了查看它对前两个单词的工作原理,但它不起作用。任何建议将不胜感激。

df['String']= df.Sentence.str.join(line.split()[2:])

标签: pythonregex

解决方案


您可以使用一次调用Series.str.replacewith

df['Sentence'].str.replace(r'(?<![^,])\s*\w+(?:\W+\w+)?\s*|\s*\w+(?:\W+\w+)?\s*(?![^,])', '')

请参阅 Pandas 演示:

>>> pattern = r'(?<![^,])\s*\w+(?:\W+\w+)?\s*|\s*\w+(?:\W+\w+)?\s*(?![^,])'
>>> df['Sentence'].str.replace(pattern, '')
0        is jumping off
1    jumped over the,is
2                      

正则表达式详细信息

  • (?<![^,])- 逗号或字符串开头必须立即出现在当前位置的左侧
  • \s*- 0+ 个空格
  • \w+- 一个或多个单词字符
  • (?:\W+\w+)?- 一个或多个非单词字符的可选出现,后跟一个或多个单词字符
  • \s*- 0+ 个空格
  • |- 或者
  • \s*- 0+ 个空格
  • \w+- 一个单词(一个或多个单词字符)
  • (?:\W+\w+)?- 一个或多个非单词字符的可选出现,后跟一个或多个单词字符
  • \s*- 0+ 个空格
  • (?![^,])- 字符串结尾,或紧跟逗号的位置。

推荐阅读