Python:截断一个句子的最后一个词? [英] Python: Cut off the last word of a sentence?

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

问题描述

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

我能想到

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

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

content = content[position-1:position+249] # 内容单词 = string.split(content, ' ')words = words[len[words] -1] # 剪切最后一个单词

非常感谢任何代码示例.

解决方案

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

一些例子:

<预><代码>>>>text = 'Python:截断一个句子的最后一个词?'>>>text.rsplit(' ', 1)[0]'Python:剪切 a 的最后一个单词'

rsplit 是反向拆分"的简写,与常规的 split 不同,它从字符串的末尾开始工作.第二个参数是要进行的最大分割数 - 例如1 的值将作为结果为您提供双元素列表(因为进行了单个拆分,导致输入字符串的两个部分).

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.

解决方案

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

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

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