Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
222 views
in Technique[技术] by (71.8m points)

python - How to print the first two words in each sentence of a text

I have string with multiple sentences.

string1 = 'I am going to the shop. I would like some cheese! I am ready to go back home!'

How can i print the first two words of each sentence? And the last two words of each sentence?

The first two words of each sentence are:
I am I would I am
The last two words of each sentence are:
the shop some cheese back home
question from:https://stackoverflow.com/questions/65942427/how-to-print-the-first-two-words-in-each-sentence-of-a-text

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Edit: To also print last two words of each sentence

import re
string1 = 'I am going to the shop. I would like some cheese! I am ready to go back home!'
split_list = re.split('[?.!]', string1)
for txt in split_list:
    print(txt.split()[:2],txt.split()[-2:] ) 

output

['I', 'am'] ['the', 'shop']
['I', 'would'] ['some', 'cheese']
['I', 'am'] ['back', 'home']
[] []

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...