加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Python > 正文

如何在python中反转部分句子?

发布时间:2020-12-20 13:13:52 所属栏目:Python 来源:网络整理
导读:我有一句话,让我们说: 敏捷的棕色狐狸跳过了懒狗 我想创建一个函数,它接受2个参数,一个句子和一个要忽略的事物列表.并且它返回带有反转词的句子,但它应该忽略我在第二个参数中传递给它的东西.这就是我现在所拥有的: def main(sentence,ignores): return '
我有一句话,让我们说:

敏捷的棕色狐狸跳过了懒狗

我想创建一个函数,它接受2个参数,一个句子和一个要忽略的事物列表.并且它返回带有反转词的句子,但它应该忽略我在第二个参数中传递给它的东西.这就是我现在所拥有的:

def main(sentence,ignores):
    return ' '.join(word[::-1] if word not in ignores else word for word in sentence.split())

但这只有在我传递第二个列表时才会起作用:

print(main('The quick brown fox jumps over the lazy dog',['quick','lazy']))

但是,我想传递一个这样的列表:

print(main('The quick brown fox jumps over the lazy dog',['quick brown','lazy dog']))

预期结果:
ehT快速棕色xof spmuj revo eht懒狗

所以基本上第二个参数(列表)将包含应忽略的句子部分.不只是单个单词.

我必须使用正则表达式吗?我试图避免它……

解决方法

我是第一个建议避免使用正则表达式的人,但在这种情况下,不使用它的复杂性大于使用它们所增加的复杂性:

import re

def main(sentence,ignores):
    # Dedup and allow fast lookup for determining whether to reverse a component
    ignores = frozenset(ignores)

    # Make a pattern that will prefer matching the ignore phrases,but
    # otherwise matches each space and non-space run (so nothing is dropped)
    # Alternations match the first pattern by preference,so you'll match
    # the ignores phrases if possible,and general space/non-space patterns
    # otherwise
    pat = r'|'.join(map(re.escape,ignores)) + r'|S+|s+'

    # Returns the chopped up pieces (space and non-space runs,but ignore phrases stay together
    parts = re.findall(pat,sentence)

    # Reverse everything not found in ignores and then put it all back together
    return ''.join(p if p in ignores else p[::-1] for p in parts)

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读