当前位置: 代码迷 >> python >> 在pandas数据框列中查询一个文本短语,该短语中可能有单词也可能没有单词
  详细解决方案

在pandas数据框列中查询一个文本短语,该短语中可能有单词也可能没有单词

热度:81   发布时间:2023-06-19 09:11:19.0

目标:在pandas数据框列中查询一个文本短语,该短语中可能有单词,也可能没有单词。 在较高级别上,短语是“ word1 word2”。 在单词1和单词2之间可能有也可能没有其他单词。

这听起来像是骗子,但是我在这里尝试了SO答案:

还有其他一些人,他们都错过了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)

第二个'\\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
  相关解决方案