Python:切断句子的最后一句话吗? [英] Python: Cut off the last word of a sentence?

查看:137
本文介绍了Python:切断句子的最后一句话吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

我能想到

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

我目前正在采用方法1,但是我不知道如何串联列表...

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.

推荐答案

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

Actually you don't need to split all words. You can split you text by last space symbol into two parts using 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将为您提供包含两个元素的列表(由于进行了一次拆分,因此产生了两个输入字符串).

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).

这篇关于Python:切断句子的最后一句话吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆