我需要知道文本中某个单词的所有位置 - 字符串中的子串。到目前为止的解决方案是使用正则表达式,但我不确定是否没有更好的,可能内置标准库策略。有任何想法吗?子串在字符串中的位置
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
为什么你的正则表达式如此复杂?也是重新是标准库的一部分吧 –