我需要知道文本中某個單詞的所有位置 - 字符串中的子串。到目前爲止的解決方案是使用正則表達式,但我不確定是否沒有更好的,可能內置標準庫策略。有任何想法嗎?子串在字符串中的位置
import re
text = "The quick brown fox jumps over the lazy dog. fox. Redfox."
links = {'fox': [], 'dog': []}
re_capture = u"(^|[^\w\-/])(%s)([^\w\-/]|$)" % "|".join(links.keys())
iterator = re.finditer(re_capture, text)
if iterator:
for match in iterator:
# fix position by context
# (' ', 'fox', ' ')
m_groups = match.groups()
start, end = match.span()
start = start + len(m_groups[0])
end = end - len(m_groups[2])
key = m_groups[1]
links[key].append((start, end))
print links
{ '狐狸':[(16,19),(45,48)], '狗':[(40,43)]}
編輯:部分的話不允許匹配 - 見狐狸Redfox不在鏈接。
謝謝。
重複http://stackoverflow.com/questions/3437059/does-python-have-a-字符串包含子字符串方法 –
@RNar這不是一個重複的原因OP尋找*所有*發生。 – alfasin
爲什麼你的正則表達式如此複雜?也是重新是標準庫的一部分吧 –