python匹配字符串中,某个词的位置

这里我用的是终端传值的方式,比如:python xxx.py "i am your friends" "am"

import re
import sys

arr = []
sentence = str(sys.argv[1])
word = str(sys.argv[2])
rr = re.compile(word, re.I)  # 不区分大小写
for match in re.finditer(rr, sentence):
    print(match)
    obj = {"start": match.start() + 1, "end": match.end(), "length": match.end() - match.start()}
    arr.append(obj)
print(arr)

注意:

rr = re.compile(word, re.I)  # 不区分大小写

将匹配词汇转为正则形式的,可以匹配出各种词汇。如果不把词汇转为正则,而是直接匹配,则匹配不到带有特殊字符的字符串的位置。

匹配结果如下所示:

 

原文地址:https://www.cnblogs.com/lxz123/p/15351585.html