【发布时间】:2018-09-16 21:47:43
【问题描述】:
目标:在 pandas 数据框列中查询一个文本短语,该短语中可能有也可能没有单词。在高层次上,一个短语是“word1 word2”。在 word1 和 word 2 之间可能有也可能没有其他词。
这听起来像是一个骗局,但是我在这里尝试了 SO 答案:
How to extract a substring from inside a string in Python?
Regular expression: matching and grouping a variable number of space separated words
Match text between two strings with regular expression
Extract text information between two define text
还有一些其他的,他们都错过了 word1 和 word2 之间没有单词的情况。
这些投票率高的解决方案都依赖于 word1 和 word2 之间的 (.+?)。
例如:word1(.+?)word2
如果 word1 和 word2 之间有 1+ 个单词,则上述方法效果很好。但是,如果 word1 和 word2 之间没有单词,那么它不会返回任何结果,但是我希望它在这种特殊情况下也能返回结果,因为文本短语包含 word1 word2。
此外,数据将被提前清理,因此无需考虑大写、逗号或其他虚假字符。
我的代码和试验如下。代替 word1 word2 我使用“pieces Delivered”作为文本短语。
请注意,他们都错过了第一个示例,即“已交付的作品”之间没有中间词。它应该返回“一些按时交付的物品”以及其他带有“件......交付”的行。
提前致谢。
import pandas as pd
df = pd.Series(['a', 'b', 'c', 'some pieces delivered on time', 'all pieces not delivered', 'most pieces were never delivered at all', 'the pieces will never ever be delivered', 'some delivered', 'i received broken pieces'])
print("Baseline - Desired results SHOULD contain:\n", df.iloc[3:7])
# The following options all miss one or more rows from the desired results.
# Just uncomment rgx = to run a regex.
rgx = r'pieces\s(.*?)\sdelivered'
#rgx = r'pieces\s(\w*)\sdelivered'
#rgx = r'pieces\s(\w*)+\sdelivered'
#rgx = r'pieces\s(\w)*\sdelivered'
#rgx = r'pieces\s(\w+\s)+\sdelivered'
#rgx = r'pieces\s(.*)\sdelivered'
#rgx = r'pieces\s+((%s).*?)\sdelivered'
df2 = df[df.str.contains(rgx)]
print("\nActual results were:\n", df2)
【问题讨论】:
-
df.replace('^((?!pieces.*delivered).)*$',float('nan'),regex=True).dropna()这应该可以工作
标签: python regex python-3.x pandas