簡體   English   中英

字符串中符號的開始和結束位置

[英]Start and End Position of symbols in a string

我試圖在字符串中找到_的開始和結束位置作為元組列表。

我使用的代碼是

sentence = 'special events _______ ______ ___ _______ ____ _____ _______ ___________ brochure subscriptions ticket guide'
symbol = '_'

position = [(match.start(),match.end()) for match in re.finditer(symbol, sentence)]

為此,獲得的輸出是

[(15, 16), (16, 17), (17, 18), (18, 19), (19, 20)..................]

如何將連續定位符號的開始和結束位置作為元組列表。

您應該添加+量詞。 由於 symbol 可能是正則表達式的特殊符號,您可能希望使用re.escape對其進行轉義。

import re

sentence = 'special events _______ ______ ___ _______ ____ _____ _______ ___________ brochure subscriptions ticket guide'
symbol = '_'

needle = f'{re.escape(symbol)}+'
position = [(match.start(),match.end()) for match in re.finditer(needle, sentence)]
print(position)

結果是[(15, 22), (23, 29), (30, 33), (34, 41), (42, 46), (47, 52), (53, 60), (61, 72)]

請注意, endMatch.end文檔中所述的匹配后的位置。

你可以這樣做:

sentence2 = ' ' + sentence[:-1]
starts = [i for i in range(len(sentence))if sentence[i] == '_' and sentence2[i] != '_' ]
ends = [i - 1 for i in range(len(sentence)) if sentence2[i] == '_' and sentence[i] != '_']
pairs = list(zip(starts, ends))
print(pairs)

輸出:

[(15, 21), (23, 28), (30, 32), (34, 40), (42, 45), (47, 51), (53, 59), (61, 71)]

這將給出一個或多個連續符號字符的子字符串中第一個和最后一個符號實例的索引。 如果您需要使用 python 切片語義的結果(開始 == 連續子字符串中第一個符號實例的索引,結束 == 緊跟該子字符串中最后一個符號實例的索引),您可以將i - 1更改為i ends的初始化行。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM