繁体   English   中英

反转 Python 字符串中的单词(包括标点符号)

[英]Reversing words in a Python string (including punctuation)

我在这里写了一个程序来反转给定句子中的单词:

def rev_each_word_in(Sentence):

print(' '.join(Word[::-1] for Word in Sentence.split()))

作为我对 Sentence 的输入,我曾经“成为或不成为这是个问题”。 这将返回以下内容:

ot eb ro ton ot eb taht si eht .noitseuq

这几乎正​​是我想要的,但是有没有办法让句号保留在句子的末尾,所以返回是:

ot eb ro ton ot eb taht si eht noitseuq.

先感谢您!

可以将一个函数作为repl参数传递给re.sub() ,因此我们可以使用它来匹配单词并反转它们:

import re

def rev_each_word_in(sentence):
    return re.sub(r'\b\S*\b', lambda m: m.group(0)[::-1], sentence)

模式\\b\\S*\\b与单词边界匹配,后跟任意数量的非空白字符,后跟单词边界。

该函数(为简便起见,为lambda)为每个匹配项使用group(0) (匹配项的完整文本),并使用切片的通常方式将其反转。

例子:

>>> rev_each_word_in('to be or not to be that is the question.')
'ot eb ro ton ot eb taht si eht noitseuq.'

>>> rev_each_word_in("whether 'tis nobler in the mind to suffer")
"rehtehw 'sit relbon ni eht dnim ot reffus"

>>> rev_each_word_in("aye, there's the rub")
"eya, s'ereht eht bur"

如您所见,这会保留单词前后的标点符号位置,同时将其保留在每个反向单词内的“正确”位置。

以下是一些丑陋之处,它们可以解决这一问题:

from string import punctuation as p
print(' '.join(w[::-1] if w[-1] not in p else w[:-1][::-1] + w[-1] for w in Sentence.split()))

如果单词中的最后一个字符不在标点符号字符串中,那么我们将完全颠倒;如果是,我们将字符串反向直到标点符号为止,然后将标点符号添加到标点符号字符串中。 打印出:

ot eb ro ton ot eb taht si eht noitseuq.

尽我所能,因为我感到羞愧:

# similar to  [::-1]
r = slice(None, None,-1)
# cut down chars!    
l = Sentence.split()
# reverse condition too and use shorter names
print(' '.join(w[:-1][r] + w[-1] if w[-1] in p else w[r] for w in l))

您的规格还不清楚,但是如果您只想在一个单词内颠倒字母,也许您可​​以尝试类似

def reverse_letters(word):
    lets = (c for c in reversed(word) if c.isalpha())
    return ''.join([c if not c.isalpha() else next(lets)
                    for c in word])

def reverse_sentence(sentence):
    words = sentence.split()
    return ' '.join([reverse_letters(word) for word in words])

这给了我

In [23]: reverse_sentence("to be or not to be, that is the question.")
Out[23]: 'ot eb ro ton ot eb, taht si eht noitseuq.'

In [24]: reverse_sentence("Don't try this at home!")
Out[24]: "tno'D yrt siht ta emoh!"

将您的方法更改为此:

def rev_each_word_in(Sentence):
    if Sentence[-1] == '.':
        Sentence = Sentence[:-1]
        print(' '.join(Word[::-1] for Word in Sentence.split())+".")
    else:
        print(' '.join(Word[::-1] for Word in Sentence.split()))
import string

def reverse(sentence):
    punctuation = set(string.punctuation)
    words = []
    for word in sentence.split():
        words.append(word.rstrip(string.punctuation)[::-1])
        if word[-1] in punctuation:
           words[-1] = words[-1]+word[-1]
    return ' '.join(words)

输出:

In [152]: reverse("to be or not to be that is the question.")
Out[152]: 'ot eb ro ton ot eb taht si eht noitseuq.'

这将适用于您句子中的任何标点符号:

In [153]: reverse("to be or not to be; that is the question.")
Out[153]: 'ot eb ro ton ot eb; taht si eht noitseuq.'

反转字符串输入中的单词-'i.like.python.very.much.' 输出=.much.very.python.like.i

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM