Python: extracting a sentence with a particular word

前端 未结 3 819
抹茶落季
抹茶落季 2021-01-20 20:42

I have a json file containing texts like:

dr. goldberg offers everything.parking is good.he\'s nice and easy to talk

How can I

3条回答
  •  南方客
    南方客 (楼主)
    2021-01-20 21:33

    You can use the standard library re module:

    import re
    line = "dr. goldberg offers everything.parking is good.he's nice and easy to talk"
    res = re.search("\.?([^\.]*parking[^\.]*)", line)
    if res is not None:
        print res.group(1)
    

    It will print parking is good.

    Idea is simple - you search for sentence starting from optional dot character ., than consume all non-dots, parking word and the rest of non-dots.

    Question mark handles the case where your sentence is in the start of the line.

提交回复
热议问题