如何使此句子反向算法更有效?

时间:2019-12-19 23:43:34

标签: python-3.x

目标是在保留标点符号的同时反转句子的单词。在我看来,它效率低下。有更好的方法吗?

def revSentence(x):
    x= x.split()
    punc = ".!?;"
    front = 0
    end = len(x)-1
    while front < end:
        fp=""
        ep=""
        if x[front][-1] in punc:
               fp =x[front][-1]
               x[front]= x[front][:-1]
        elif x[end][-1] in punc: 
            ep =x[end][-1]
            x[end]= x[end][:-1]
        temp = x[front] + ep
        x[front] = x[end]+ fp
        x[end] = temp
        front+= 1
        end-= 1
    return ' '.join(x)

print(revSentence("I like eggs. And Ice cream!"))

预期输出:

cream Ice And. eggs like I!

1 个答案:

答案 0 :(得分:0)

使用正则表达式模式将标点符号与单词分开可能是一种较短的方法:

import re
def revSentence(s):
    words = reversed(re.split(r'[\W]+', s))
    punc = re.split(r'[\w]+', s)
    rev = "".join(w + punc[i] for i, w in enumerate(words))
    return rev

print(revSentence("I like eggs. And Ice cream!"))

还将打印

cream Ice And. eggs like I!