[英]How to find the longest consecutive string of values in pandas dataframe
[英]Using Regex to find longest consecutive match in a string
我正在嘗試使用正則表達式實現以下目標:
String = "APPLEORANGEORANGEAPPLEAPPLEAPPLEBANANABANANABANANAAPPLEBANANA"
如果比賽是
重新編譯 = [“蘋果”]
輸出應該是 3,因為這是最長的連續匹配。
意思是,我希望其他兩次不連續或不是最長連續批次的“APPLE”被忽略。 如果只有單個、分隔的匹配項,則輸出應為 1,因為沒有一個是連續的。
我在文檔中找不到任何只匹配連續結果的過濾器,對不起,如果這是一個初學者問題並且我還沒有意識到一個功能。
您應該查找字符串“APPLE”的一個或多個連續出現的所有匹配項,以下正則表達式將執行此操作:
(?:APPLE)+
然后按長度降序對它們進行排序。 取最長匹配(即第一個匹配)並除以 5('APPLE' 中的字符數),這將告訴您在最長匹配中找到了多少次連續出現的 'APPLE':
import re
s = "APPLEORANGEORANGEAPPLEAPPLEAPPLEBANANABANANABANANAAPPLEBANANA"
matches = sorted(re.findall(r'(?:APPLE)+', s), reverse=True)
if matches:
print(len(matches[0]) // 5)
else:
print(0)
印刷:
3
Booboo 已經提供了一個最佳解決方案,但是當我寫這篇文章之前,我注意到我無論如何都會發布它。
import re
def get_max_consecutive_match_count(word, text):
if word and text:
pattern = re.compile(f'(?:{re.escape(word)})+')
lengths = [m.end() - m.start() for m in re.finditer(pattern, text)]
return max(lengths) // len(word) if lengths else 0
str = 'APPLEORANGEORANGEAPPLEAPPLEAPPLEBANANABANANABANANAAPPLEBANANA'
print(get_max_consecutive_match_count('APPLE', str))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.