Python: extracting a sentence with a particular word

前端 未结 3 815
抹茶落季
抹茶落季 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:21

    you can use nltk.tokenize :

    from nltk.tokenize import sent_tokenize
    from nltk.tokenize import word_tokenize
    f=open("test_data.json").read()
    sentences=sent_tokenize(f)
    my_sentence=[sent for sent in sentences if 'parking' in word_tokenize(sent)] #this gave you the all sentences that your special word is in it ! 
    

    and as a complete way you can use a function :

    >>> def sentence_finder(text,word):
    ...    sentences=sent_tokenize(text)
    ...    return [sent for sent in sentences if word in word_tokenize(sent)]
    
    >>> s="dr. goldberg offers everything. parking is good. he's nice and easy to talk"
    >>> sentence_finder(s,'parking')
    ['parking is good.']
    

提交回复
热议问题