Python: Cut off the last word of a sentence?

2019-01-22 17:21发布

What's the best way to slice the last word from a block of text?

I can think of

  1. Split it to a list (by spaces) and removing the last item, then reconcatenating the list.
  2. Use a regular expression to replace the last word.

I'm currently taking approach #1, but I don't know how to concatenate the list...

content = content[position-1:position+249] # Content
words = string.split(content, ' ')
words = words[len[words] -1] # Cut of the last word

Any code examples are much appreciated.

7条回答
啃猪蹄的小仙女
2楼-- · 2019-01-22 17:55

You should definitely split and then remove the last word because a regex will have both more complications and unnecessary overhead. You can use the more Pythonic code (assuming content is a string):

' '.join(content.split(' ')[:-1])

This splits content into words, takes all but the last word, and rejoins the words with spaces.

查看更多
萌系小妹纸
3楼-- · 2019-01-22 17:56

If you want to keep your current method, use ' '.join(words) to concatenate the list.

You also might want to replace words = words[len[words -1] with words = words[:-1] to make use of list slicing.

查看更多
趁早两清
4楼-- · 2019-01-22 17:57

' '.join(words) will put the list back together.

查看更多
够拽才男人
5楼-- · 2019-01-22 18:02

Actually you don't need to split all words. You can split you text by last space symbol into two parts using rsplit.

Some example:

>>> text = 'Python: Cut of the last word of a sentence?'
>>> text.rsplit(' ', 1)[0]
'Python: Cut of the last word of a'

rsplit is a shorthand for "reverse split", and unlike regular split works from the end of a string. The second parameter is a maximum number of splits to make - e.g. value of 1 will give you two-element list as a result (since there was a single split made, which resulted in two pieces of the input string).

查看更多
聊天终结者
6楼-- · 2019-01-22 18:07

Get last index of space and splice the string

>>> text = 'Python: Cut of the last word of a sentence?'
>>> text[:text.rfind(' ')]
'Python: Cut of the last word of a'
查看更多
相关推荐>>
7楼-- · 2019-01-22 18:10

If you like compactness:

' '.join(content.split(' ')[:-1]) + ' ...'
查看更多
登录 后发表回答