qwe*_*rty 45 python split concatenation cpu-word text-segmentation
从文本块中切出最后一个单词的最佳方法是什么?
我能想到
我目前正在采取方法#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
将给出两个元素列表作为结果(因为进行了单个分割,这导致两个输入字符串).
mur*_*d99 12
你肯定应该拆分然后删除最后一个单词,因为正则表达式会带来更多的复杂性和不必要的开销.您可以使用更多的Pythonic代码(假设内容是一个字符串):
' '.join(content.split(' ')[:-1])
Run Code Online (Sandbox Code Playgroud)
这会将内容分成单词,除了最后一个单词之外的所有内容,并使用空格重新加入单词.