【发布时间】:2012-12-14 20:10:34
【问题描述】:
我正在尝试创建一个 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 语句列表)或考虑多个符号并将它们全部移动。
我一直在玩正则表达式,但仍然没有一个可行的解决方案,我一直在寻找一种方法来更改符号的索引,但仍然没有...
如果我可以提供更多详细信息,请告诉我。
谢谢!
【问题讨论】:
-
当您想全部移动时,请显示多个符号的示例。
-
请注意,这是“跳跃”,而不是“跳跃”:)
-
我没有多个符号的示例,这就是我寻求帮助的原因。
-
然后,我看到你设法移动了 ',' 和 '.'到单词的开头,我不明白有什么问题。
-
问题是这不会移动'...'或'!!!',我不想为每个符号写一个新的if语句。
标签: python string plugins sublimetext2 reverse