【问题标题】:Python: Moving a symbol to the start of the string?Python:将符号移动到字符串的开头?
【发布时间】: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


【解决方案1】:

如果您是 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', '.']

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

【讨论】:

  • 谢谢!这真的很有帮助,也是我从未想过(或知道)的一种方式。现在,当文本被翻译时,它会从空数组中添加所有额外的空白。有没有办法把它们取出来? (我是正则表达式的新手,我仍在努力弄清楚一切的含义)
  • @Sintyche 您可以使用列表理解删除结果中的多余空格。类似[elem for elem in re.sub(r'\b', '\f', sentence).split('\f') if elem.strip()].
【解决方案2】:

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

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-11-08
    • 2023-01-26
    • 2019-09-19
    • 2021-11-06
    • 2014-08-03
    相关资源
    最近更新 更多