我写了一个程序来反转给定句子中的单词:
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.
提前谢谢!
答案 0 :(得分:3)
可以将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"
正如您所看到的,这会在字词之前或之后立即保留标点符号的位置,同时将其保持在每个反转字词内的“正确”位置。
答案 1 :(得分:1)
这里有一些丑陋的事情在一行中处理:
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))
答案 2 :(得分:1)
您的规格仍然不清楚,但如果您只想在一个单词中翻转字母,也许您可以尝试类似
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!"
答案 3 :(得分:0)
将您的方法更改为:
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()))
答案 4 :(得分:0)
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.'