Python 巨蟒:切掉一句话的最后一个字?

Python 巨蟒:切掉一句话的最后一个字?,python,split,concatenation,word,text-segmentation,Python,Split,Concatenation,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 非常感谢任何代码示例

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

我能想到

  • 将其拆分为一个列表(按空格),删除最后一项,然后重新连接该列表
  • 使用正则表达式替换最后一个单词
  • 我目前正在采用方法1,但我不知道如何连接列表

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

    非常感谢任何代码示例。

    ''。join(words)
    将重新组合列表。

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


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

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

    例如:

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

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

    您肯定应该拆分并删除最后一个单词,因为正则表达式将有更多的复杂性和不必要的开销。您可以使用更具Python风格的代码(假设内容是字符串):


    这会将内容拆分为多个单词,除最后一个单词外,其余单词都会被拆分,并用空格重新连接。

    如果您喜欢紧凑性:

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


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

    >>> text = 'Python: Cut of the last word of a sentence?'
    >>> text[:text.rfind(' ')]
    'Python: Cut of the last word of a'
    

    我想,如果你的单词不只是被空格分割,正则表达式会给你带来好处。否则,rsplit是你的选择。如果你觉得有必要的话,可以使用其他一些答案来说明rsplit是反向分割(不是正则表达式分割)1是maxsplit。只是一个需要注意的边缘大小写。如果句子中只有一个单词,这个解决方案不会删除任何内容。这个解决方案在小字符串上比公认的答案快15-20%。我仍然很努力,还是一个新手,但我确实做到了。希望它能帮助一些人,谢谢。我添加了变量S1 O1 N1以使它更可读,因为他们没有回答原来的问题。
    import re
    
    print ' '.join(re.findall(r'\b\w+\b', text)[:-1])
    
    >>> text = 'Python: Cut of the last word of a sentence?'
    >>> text[:text.rfind(' ')]
    'Python: Cut of the last word of a'
    
            
    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"