Python:切断句子的最后一个字?

qwe*_*rty 45 python split concatenation cpu-word text-segmentation

从文本块中切出最后一个单词的最佳方法是什么?

我能想到

  1. 将其拆分为一个列表(按空格)并删除最后一项,然后重新合并列表.
  2. 使用正则表达式替换最后一个单词.

我目前正在采取方法#1,但我不知道如何连接列表...

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

任何代码示例都非常感谢.

Rom*_*huk 133

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

一些例子:

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

rsplit是"反向分割"的简写,而不像split字符串末尾的常规作品.第二个参数是要进行的最大分割数 - 例如,值1将给出两个元素列表作为结果(因为进行了单个分割,这导致两个输入字符串).

  • 如果觉得有必要注意rsplit是反向分割(不是正则表达式分割)而1是maxsplit,则使用其他一些答案. (3认同)

mur*_*d99 12

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

' '.join(content.split(' ')[:-1])
Run Code Online (Sandbox Code Playgroud)

这会将内容分成单词,除了最后一个单词之外的所有内容,并使用空格重新加入单词.


Gia*_*nio 5

如果你喜欢紧凑:

' '.join(content.split(' ')[:-1]) + ' ...'
Run Code Online (Sandbox Code Playgroud)