目标:在pandas数据框列中查询一个文本短语,该短语中可能有单词,也可能没有单词。在较高级别上,短语是“ word1 word2”。在单词1和单词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,我使用“已交付的邮件”作为文本短语。
请注意,他们都错过了第一个示例,其中“已交付的作品”之间没有中间的单词。它应返回“按时交货的某些零件”,以及其他行与“按时交货的零件”。
先谢谢了。
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)
答案 0 :(得分:1)
第二个'\s'
的位置错误。仅当两个单词不相邻时才需要它:
df[df.str.contains(r'pieces\s(?:.+?\s)?delivered')]
#3 some pieces delivered on time
#4 all pieces not delivered
#5 most pieces were never delivered at all
#6 the pieces will never ever be delivered