简体   繁体   中英

how do i get the sentence in a document containing a particular word using python?

From an entire text, I want to extract the whole sentence in which a given word appears. For example:

text = "The cat ran. I am Sam. Whoop dee doo."
output = get_sentence("am")

Should yield --> "I am Sam."

You can use nltk<\/code> library to tokenize the sentence

nltk.download("punkt")
text = "Hello, I am Taksh. Nice to meet you Mr. Panchal. 
                    You scored 82.5 % in test"
nltk.tokenize.sent_tokenize(text)
>> ['Hello, I am Taksh.',
    'Nice to meet you Mr. Panchal.',
    'You scored 82.5 % in test']

Split the string into sentences then search each for the phrase

text = text.split('. ')
for s in text:
    if searchWord in s:
        return s + "."
    return "Search word not found"
text = "The cat ran. I am Sam. Whoop dee doo."
text =  text.split('.')
data = input("Enter the String want to search")
for i in text:
   if data in i:
      print(i )
   else:
      print("search word is not present")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM