我試圖在混合 OR 和 AND 的同時使用 str.contains 識別給定字串中的子字串
我知道 OR 可以表示為 |
str.contains("error|break|insufficient")
并且 AND 可以用 AND 表示
str.contains("error|break|insufficient") & str.contains("status")
我想將 OR 和 AND 混合在一起。示例是識別具有“錯誤”或“中斷或”(“不足”和“狀態”)的字串
所以對于像“錯誤中斷不足”這樣的句子->它就能識別。但現在不能因為句子中沒有“狀態”
uj5u.com熱心網友回復:
一種方法:
import pandas as pd
# toy data
s = pd.Series(["hello", "world", "simple", "error", "break", "insufficient something status", "status"])
# create and mask
insufficient_and_status = s.str.contains("insufficient") & s.str.contains("status")
# create or mask
break_or_error = s.str.contains("error|break", regex=True)
# or the two mask
mask = break_or_error | insufficient_and_status
res = s[mask]
print(res)
輸出
3 error
4 break
5 insufficient something status
dtype: object
替代方案,使用單個正則運算式:
mask = s.str.contains("error|break|(insufficient. status|status. insufficient)", regex=True)
res = s[mask]
print(res)
替代方案基于這樣一個事實:如果字串包含不充分和狀態,那么至少有一個模式insufficient. status或status. insufficient匹配(即或不充分首先出現或狀態出現)
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/316103.html
上一篇:JavascriptregEx洗掉除特殊字符之間的所有括號
下一篇:從串列中過濾/洗掉給定模式的單詞
