2011-06-07 108 views
33

从文本块中切出最后一个单词的最佳方式是什么?Python:切断句子的最后一个单词?

我能想到它

  1. 斯普利特的列表(按空格),并删除最后一个项目,然后reconcatenating列表。
  2. 使用正则表达式替换最后一个单词。

我目前录取办法#1,但我不知道如何连接列表...

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

任何代码示例大加赞赏。

回答

105

其实你不需要拆分所有单词。您可以使用rsplit将最后一个空格符号的文字分为两部分。

一些示例:

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

rsplit是“反向分割”的简写,而不像从字符串的结尾经常split作品。第二个参数是要分割的最大数量 - 例如值1会给你两个元素的列表(因为有一个单独的分割,导致了两个输入字符串)。

+2

与一些其他的答案,如果觉得有必要要注意rsplit是反向分割(不是正则表达式分割),1是maxsplit。 – 2016-06-30 16:36:31

+1

@ duckman_1991好点 - 延长了答案。 – 2018-01-16 17:14:57

2

' '.join(words)将列表重新放在一起。

4

如果要保留当前的方法,请使用' '.join(words)连接列表。

您也可能想用words = words[:-1]替换words = words[len[words -1]以利用列表切片。

7

你应该明确地拆分,然后删除最后一个词,因为正则表达式会有更多的复杂性和不必要的开销。您可以使用更Python代码(假设的内容是一个字符串):

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

此拆分成的内容的话,通吃但最后一个字,并重新加入与空间的话。

5

如果你喜欢紧凑:

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

OR

import re 

print ' '.join(re.findall(r'\b\w+\b', text)[:-1]) 
+0

我想这个正则表达式会给你带来好处,当你的单词不仅被空白分割时。否则rsplit是你的选择。 – 2011-06-07 14:52:47

0

获取的空间最后一个索引和拼接字符串

>>> text = 'Python: Cut of the last word of a sentence?' 
>>> text[:text.rfind(' ')] 
'Python: Cut of the last word of a' 
相关问题