3

我正在尝试创建一个 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 语句列表)或考虑多个符号并将它们全部移动。

我一直在玩正则表达式,但仍然没有一个可行的解决方案,我一直在寻找一种方法来更改符号的索引,但仍然没有......

如果我可以提供更多详细信息,请告诉我。

谢谢!

4

2 回答 2

0

如果您import re可以将split()行更改为在分词上拆分\b

words = re.sub(r'\b', '\f', sentence).split('\f')

看看这个为什么你不能只是split(r'\b')。以上将为您提供:

['', 'The', ' ', 'quick', ' ', 'brown', ' ', 'fox', ', ', 'jumps', ' ', 'over', ' ', 'the', ' ', 'lazy', ' ', 'dog', '.']

然后您可以轻松地将其反转并将您的符号放在正确的位置。

于 2012-12-14T20:33:57.690 回答
0

我希望正则表达式是一种更好的方法,但如果它有帮助......

你可以有一个你调用的函数来代替使用 endswith ...

def ends_with_punctuation(in_string):
    punctuation = ['.', ',', ':', ';', '!', '?']
    for p in punctuation:
        if in_string.endswith(p):
            return True
    return False
于 2012-12-14T21:06:44.373 回答