Python:将符号移动到字符串的开头?

时间:2012-12-14 20:10:35

标签: python string plugins sublimetext2 reverse

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

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

如果我能提供更多详情,请告诉我。

谢谢!

2 个答案:

答案 0 :(得分:0)

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

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

See this为什么你不能只split(r'\b')。以上将给你:

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

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

答案 1 :(得分:0)

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

你可以使用一个函数代替使用endswith ...

def ends_with_punctuation(in_string):
    punctuation = ['.', ',', ':', ';', '!', '?']
    for p in punctuation:
        if in_string.endswith(p):
            return True
    return False