简体   繁体   English

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

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

I wrote a program to reverse the words in a given sentence here:我在这里写了一个程序来反转给定句子中的单词:

def rev_each_word_in(Sentence):

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

As my input for Sentence I used "to be or not to be that is the question."作为我对 Sentence 的输入,我曾经“成为或不成为这是个问题”。 This returns the following:这将返回以下内容:

ot eb ro ton ot eb taht si eht .noitseuq

It's almost exactly what I want, but is there a way that the period could remain at the end of the sentence, so the return would be:这几乎正​​是我想要的,但是有没有办法让句号保留在句子的末尾,所以返回是:

ot eb ro ton ot eb taht si eht noitseuq.

Thank you in advance!先感谢您!

It's possible to pass a function as the repl argument to re.sub() , so we can use that to match words and reverse them: 可以将一个函数作为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)

The pattern \\b\\S*\\b matches a word boundary, followed by an arbitrary number of non-whitespace characters, followed by a word boundary. 模式\\b\\S*\\b与单词边界匹配,后跟任意数量的非空白字符,后跟单词边界。

The function (a lambda, for brevity) takes group(0) (the complete text of the match) for each match, and reverses it the usual way using slicing. 该函数(为简便起见,为lambda)为每个匹配项使用group(0) (匹配项的完整文本),并使用切片的通常方式将其反转。

Examples: 例子:

>>> 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"

As you can see, this preserves the position of punctuation immediately before or after words, while maintaining it in the "correct" position inside each reversed word. 如您所见,这会保留单词前后的标点符号位置,同时将其保留在每个反向单词内的“正确”位置。

Here comes some ugliness that takes care of this in one line: 以下是一些丑陋之处,它们可以解决这一问题:

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()))

Where we reverse fully if the last character in a word is not in the punctuation string and if it is we reverse the string up until the punctuation and then add the punctuation to it. 如果单词中的最后一个字符不在标点符号字符串中,那么我们将完全颠倒;如果是,我们将字符串反向直到标点符号为止,然后将标点符号添加到标点符号字符串中。 prints out: 打印出:

ot eb ro ton ot eb taht si eht noitseuq.

Slimming it down as much as I can because I'm ashamed of it: 尽我所能,因为我感到羞愧:

# 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))

Your specifications are still unclear, but if you want only the letters to be reversed within a word, maybe you could try something like 您的规格还不清楚,但是如果您只想在一个单词内颠倒字母,也许您可​​以尝试类似

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])

which gives me 这给了我

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!"

Change your method to this: 将您的方法更改为此:

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)

Output: 输出:

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.'

And this will work for any punctuation in your sentence: 这将适用于您句子中的任何标点符号:

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.'

reverse a word in string input-'i.like.python.very.much.'反转字符串输入中的单词-'i.like.python.very.much.' output=.much.very.python.like.i输出=.much.very.python.like.i

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

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