python匹配字符串中某个词的开始位置和结束位置
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)