user12167490
user12167490

Reputation: 27

The output of sentences extracted by key words

I am new to Python. I have trouble figuring out the format of the extracted sentences by several key words. There are several sentences extracted. How to convert the output of several sentences to one string?

For example:

search_keywords=['my family','love my']
text = "my family is good. I love my family. I am happy."
sentences = text.split(".")

for sentence in sentences:
    if (any(map(lambda word: word in sentence, search_keywords))):  
        print (sentence)
        count = len(sentence.split()) 
        print(count)

The output is:

my family is good
4
 I love my family
4

How to combine the two extracted sentences as one string, so the total count equals 8 like the following:

my family is good. I love my family. 
8

Any help is appreciated.

Upvotes: 0

Views: 72

Answers (3)

Romain Reboulleau
Romain Reboulleau

Reputation: 306

Use the join method for strings:

outp = []
count = 0
for sentence in sentences:
    if (any(map(lambda word: word in sentence, search_keywords))):  
        outp.append(sentence)
        count += len(sentence.split()) 
print('. '.join(outp) + '.')
print(count)

You choose the separator string and apply the join method providing the list to be separated by the string.

Upvotes: 0

ExplodingGayFish
ExplodingGayFish

Reputation: 2897

How about this:

result = []
result_count = 0
for sentence in sentences:
    if (any(map(lambda word: word in sentence, search_keywords))):  
        result.append(sentence)
        result_count += len(sentence.split())
print('. '.join(result) + '.')
print(result_count)
#my family is good.  I love my family.
#8

Upvotes: 0

user12066865
user12066865

Reputation:

Let me correct your python code

#your data
search_keywords=['my family','love my']
text = "my family is good. I love my family. I am happy."
sentences = text.split(".")

#initialise
total_count = 0
final_sentence = ""

#every sentences
for sentence in sentences:
    if (any(map(lambda word: word in sentence, search_keywords))):  
        #add the count to total_count
        total_count += len(sentence.split()) 
        #add the sentence to final sentence
        final_sentence += sentence+'.'

#print the final_sentence and total_count
print(final_sentence)
print(total_count)

Upvotes: 1

Related Questions