python - 递归拆分包含一组已定义前缀的字符串 - Python

标签 python string recursion split prefix

如果我有一个可以附加到字符串的前缀列表,我如何将一个字符串拆分为它的前缀和下一个子字符串中的其他字符。例如:

prefixes = ['over','under','re','un','co']

str1 = "overachieve"
output: ["over","achieve"]

str2 = "reundo"
output = ["re","un","do"]

是否有更好的方法来完成上述任务,可能使用正则表达式或一些字符串函数,而不是:

str1 = "reundo"
output = []

for x in [p for p in prefixes if p in str1]:
    output.append(x)    
    str1 =  str1.replace(x,"",1)
output.append(str1)

最佳答案

正则表达式是搜索许多替代前缀的有效方法:

import re

def split_prefixes(word, prefixes):
    regex = re.compile('|'.join(sorted(prefixes, key=len, reverse=True)))
    result = []
    i = 0
    while True:
        mo = regex.match(word, i)
        if mo is None:
            result.append(word[i:])
            return result
        result.append(mo.group())
        i = mo.end()


>>> prefixes = ['over', 'under', 're', 'un', 'co']
>>> for word in ['overachieve', 'reundo', 'empire', 'coprocessor']:
        print word, '-->', split_prefixes(word, prefixes)

overachieve --> ['over', 'achieve']
reundo --> ['re', 'un', 'do']
empire --> ['empire']
coprocessor --> ['co', 'processor']

关于python - 递归拆分包含一组已定义前缀的字符串 - Python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14558034/

相关文章:

python - 模板中的 Django substr/substring

Python 分块 CSV 文件多处理

python - 如何打印从 scrapy shell 中的循环派生的结果?

python - 树遍历,递归比python中的迭代更快?

flash - 没有重复的AS3递归对象扫描?

java - 当我将此指针推到 Deque/ArrayList 上时,如果它显然不是 Null,为什么会出现 NullPointerException

python - 模块未找到错误 : No module named 'matplotlib' even though the package is installed

string - 如何在elisp中将字符串居中?

python - 如何对字符串和 int 值数组、按字母顺序和 "reversed"字母顺序的多个属性进行排序

string - 在文本文件中查找具有特殊字符的字符串并在每次出现之前添加换行符