我正在尝试创建一个 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 语句)或解释多个符号并将它们全部移动。
我一直在研究正则表达式,但仍然没有找到有效的解决方案,而且我一直在寻找一种方法来更改符号的索引,但仍然一无所获...</p>
如果我可以提供更多详细信息,请告诉我。
谢谢!
最佳答案
如果您import re
,您可以更改您的split()
行以在单词break \b
上拆分:
words = re.sub(r'\b', '\f', sentence).split('\f')
See this为什么你不能只是 split(r'\b')
。以上将为您提供:
['', 'The', ' ', 'quick', ' ', 'brown', ' ', 'fox', ', ', 'jumps', ' ', 'over', ' ', 'the', ' ', 'lazy', ' ', 'dog', '.']
然后您可以轻松反转并将您的符号放在正确的位置。
关于Python:将符号移动到字符串的开头?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13885568/