Skip to main content
 首页 » 编程设计

Python如何跳过字符串中某些符号标记的部分

2025年05月04日19Terrylee

我正在尝试通过将单词列表中的单词与句子进行一对一匹配来重建句子:

text='acatisananimal' 
words=['cat','is','an','a','animal'] 
 
for i in words: 
    if i in text: 
        final=text.replace(i,' '+i) 
        text=final 
print(final) 

预期的输出是这样的:

a cat is an animal 

如果我运行我的代码,'animal' 中的 'a' 和 'an' 也将不可避免地分开。 所以我想把单词列表按长度排序,先搜索长的单词。

words.sort(key=len) 
words=words[::-1] 

然后我想用特殊符号标记长单词,并希望程序可以跳过我标记的部分。例如:

acatisan%animal& 

最后我会擦掉符号。但是我被困在这里了。我不知道如何让程序跳过 '%' 和 '&' 之间的某些部分。谁能帮我??还是有更好的方法来解决间距问题?非常感谢!

**另一种情况,如果文本中包含单词列表中未包含的单词怎么办?我该如何处理?

text=‘wowwwwacatisananimal’ 

请您参考如下方法:

一种更通用的方法是在开头查找所有有效单词,将它们分开并探索其余字母,例如:

def compose(letters, words): 
    q = [(letters, [])] 
    while q: 
        letters, result = q.pop() 
        if not letters: 
            return ' '.join(result) 
        for word in words: 
            if letters.startswith(word): 
                q.append((letters[len(word):], result+[word])) 
 
>>> words=['cat','is','an','a','animal'] 
>>> compose('acatisananimal', words) 
'a cat is an animal' 

如果可能存在多种可能的句子组合,将其转换为生成器并将 return 替换为 yield 以生成所有匹配的句子组合会很简单。

人为的例子(只需将 return 替换为 yield):

>>> words=['adult', 'sex', 'adults', 'exchange', 'change'] 
>>> list(compose('adultsexchange', words)) 
['adults exchange', 'adult sex change']