Find a specific character in Python and extract the sentence it belongs to

Asked 2 years ago, Updated 2 years ago, 14 views

What words should I find in a text file and how should I extract the sentences that contain the words?

For example, find the word "sky" The sky is blue. An airplane is flying in the sky. The sky is full of stars. I want to extract each of these sentences.

I think I need to use for, while, if, but I don't have a clue what to do. I saw a site called Jump to Python and followed it one by one, and I even ran and saved files, and regular expressions are not available.

python

2022-09-22 08:59

2 Answers

I'm more curious about the environment where I can't use regular expressions.

If a regular expression is not available, a simple iteration is required.

First of all, the conditions of the sentence must be clear.

It should be clear whether the line unit is a sentence or a good point unit. Only then can we separate sentences into units.

For example,

The sky is blue. An airplane is flying in the sky. The sky is full of stars.

There are three sentences above. The separation condition of the three sentences is punctuation (.).

So you can break it down into sentences in a paragraph, and it's easy to find the word "sky" in a sentence and work on existence.


2022-09-22 08:59

It is possible to do something as simple as the following.

cat sample.txt
An airplane is flying in the sky. 
It's hot in summer.
The sky is full of stars.
Winter is cold.


with open('sample.txt') as f:
    lines = f.readlines()
    print([line.rstrip() for lines if line.find('sky')])


2022-09-22 08:59

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.