Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/298.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在Python字符串中反转单词(包括标点符号)_Python_String_Python 3.x - Fatal编程技术网

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

在Python字符串中反转单词(包括标点符号),python,string,python-3.x,Python,String,Python 3.x,我写了一个程序来反转给定句子中的单词: def rev_each_word_in(Sentence): print(' '.join(Word[::-1] for Word in Sentence.split())) 作为我对句子的输入,我使用了“生存还是毁灭,这就是问题所在”。这将返回以下内容: ot eb ro ton ot eb taht si eht .noitseuq 这几乎正是我想要的,但是有没有一种方法可以让句号保持在句子的末尾,所以返回结果是: ot eb ro ton o

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

def rev_each_word_in(Sentence):

print(' '.join(Word[::-1] for Word in Sentence.split()))
作为我对句子的输入,我使用了“生存还是毁灭,这就是问题所在”。这将返回以下内容:

ot eb ro ton ot eb taht si eht .noitseuq
这几乎正是我想要的,但是有没有一种方法可以让句号保持在句子的末尾,所以返回结果是:

ot eb ro ton ot eb taht si eht noitseuq.

提前谢谢你

将您的方法更改为:

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()))
输出:

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

以下是一些丑陋之处,它们在一行中解决了这一问题:

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

可以将函数作为
repl
参数传递给,因此我们可以使用该函数匹配单词并反转它们:

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)为每个匹配获取(匹配的完整文本),并使用切片的常用方法将其反转

示例:

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


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

这仅适用于句子末尾的单个句点。正确。这似乎是OP想要的。那么你想让“不”变成“不”?你想让所有标点保持在相同的位置吗?很好!(至少,如果你已经正确地解释了OP想要什么…)
>>> 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"