简体   繁体   English

如何打印文本每个句子中的前两个单词

[英]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

Try this one:试试这个:

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

# First two words
print('\nFirst two words')
print(' '.join(string1.split()[:2]))

# Last two words
print('\nLast two words')
print(' '.join(string1.split()[-2:]))

# First two and Last two with something inside...
print('\nFirst + something + last two words')
print(' '.join(string1.split()[:2]) + ' ...something... ' + ' '.join(string1.split()[-2:]))

Prints:印刷:

First two words
I am

Last two words
back home!

First + something + last two words
I am ...something... back home!

There are probably a hundred ways to do this but the first one that comes to mind for me would be to use the strings split() method.可能有一百种方法可以做到这一点,但我想到的第一个方法是使用字符串 split() 方法。 This will split the string up into a list and each element will be a word这会将字符串拆分为一个列表,每个元素都是一个单词

first_2_words = string1.split()[0:1] first_2_words = string1.split()[0:1]

this will split the string by the spaces and only grab the first 2 words这将用空格分割字符串,只抓取前 2 个单词

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 output

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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