59

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

我能想到

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

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

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

非常感谢任何代码示例。

4

10 回答 10

173

实际上,您不需要拆分所有单词。您可以使用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字符串末尾的常规作品不同。第二个参数是要进行的最大拆分数 - 例如,值 of1将为您提供双元素列表作为结果(因为进行了单个拆分,导致输入字符串有两段)。

于 2011-06-07T14:32:41.623 回答
17

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

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

这会将内容拆分为单词,获取除最后一个单词之外的所有单词,并用空格重新连接单词。

于 2011-06-07T14:32:54.633 回答
6

如果你喜欢紧凑:

' '.join(content.split(' ')[:-1]) + ' ...'
于 2011-06-07T14:35:43.880 回答
4

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

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

于 2011-06-07T14:31:33.567 回答
4

或者

import re

print ' '.join(re.findall(r'\b\w+\b', text)[:-1])
于 2011-06-07T14:36:30.273 回答
3

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

于 2011-06-07T14:28:29.210 回答
3

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

>>> text = 'Python: Cut of the last word of a sentence?'
>>> text[:text.rfind(' ')]
'Python: Cut of the last word of a'
于 2017-11-15T10:02:38.680 回答
1
        
def replace_ending(sentence, old, new):
    S1 = sentence
    O1 = old
    N1 = new
    # Check if the old string is at the end of the sentence 
    if O1 in S1:
        # Using i as the slicing index, combine the part
        # of the sentence up to the matched string at the 
        # end with the new string
        i = S1.rsplit(' ',1)[0] + str(" ") + N1     
        new_sentence = i
        return new_sentence

    # Return the original sentence if there is no match 
    return sentence
    
print(replace_ending("It's raining cats and cats", "cats", "dogs")) 
# Should display "It's raining cats and dogs"

于 2020-12-19T01:54:43.483 回答
0

另一个变体是使用参数“args *”

例如:

def truncate_sentences(length, *sentences):
  for sentence in sentences:
    print(sentence[:length])

#call function

truncate_sentences(8, "What's going on here", "Looks like we've been cut off")

会输出:

"What's g"
"Looks li"

让我们分解一下:

  1. 我们的函数truncate_sentences()定义了两个参数。第一个是一个length参数,它将指定我们要保留多少个字符。第二个是sentences与解包运算符配对的称为参数,表示它将采用可变数量的参数。
  2. 在函数的每次迭代中,我们循环通过sentences参数创建的元组(因为它与解包运算符配对)并根据提供的length参数对句子执行切片。这迫使sentences元组中的每个值的长度都被缩短。
于 2021-08-31T14:16:14.570 回答
0

下面试试,

def replace_ending(sentence, old, new):
# Check if the old string is at the end of the sentence 
if sentence.endswith(old):
    # Using i as the slicing index, combine the part
    # of the sentence up to the matched string at the 
    # end with the new string
    i = sentence.rsplit(' ',1)[0] + str(" ")
    new_sentence = i + new
    return new_sentence

# Return the original sentence if there is no match 
return sentence
于 2022-02-23T08:46:09.063 回答