Search in a string and obtain the 2 words before and after the match in Python

后端 未结 4 1954
伪装坚强ぢ
伪装坚强ぢ 2021-01-19 15:39

I\'m using Python to search some words (also multi-token) in a description (string).

To do that I\'m using a regex like this

    result = re.search(w         


        
4条回答
  •  南笙
    南笙 (楼主)
    2021-01-19 16:40

    How about string operations?

    line = 'Parking here is horrible, this shop sucks.'
    
    before, term, after = line.partition('here is')
    before = before.rsplit(maxsplit=2)[-2:]
    after = after.split(maxsplit=2)[:2]
    

    Result:

    >>> before
    ['Parking']
    >>> after
    ['horrible,', 'this']
    

提交回复
热议问题