我正在尝试创建一个 Sublime Text 插件(使用 python)来反转所选字符串中单词的顺序。我的主要功能正常工作,但现在我的问题是单词末尾的每个符号(句点、逗号、问号等)都保持原位,我的目标是让所有内容正确反转,以便符号移动到单词的开头。
def run(self, edit):
selections = self.view.sel()
# Loop through multiple text selections
for location in selections:
# Grab selection
sentence = self.view.substr(location)
# Break the string into an array of words
words = sentence.split()
# The greasy fix
for individual in words:
if individual.endswith('.'):
words[words.index(individual)] = "."+individual[:-1]
# Join the array items together in reverse order
sentence_rev = " ".join(reversed(words))
# Replace the current string with the new reversed string
self.view.replace(edit, location, sentence_rev)
# The quick brown fox, jumped over the lazy dog.
# .dog lazy the over jumped ,fox brown quick The
我已经能够遍历每个单词并使用 endswith() 方法进行快速修复,但这不会找到多个符号(没有长长的 if 语句列表)或考虑多个符号并将它们全部移动。
我一直在玩正则表达式,但仍然没有一个可行的解决方案,我一直在寻找一种方法来更改符号的索引,但仍然没有......
如果我可以提供更多详细信息,请告诉我。
谢谢!