python - 如何在 python 中反转句子的部分内容?

标签 python python-3.x

我有一句话,比方说:

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

我想创建一个函数,它接受 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 quick brown xof spmuj revo eht lazy dog

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

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

最佳答案

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

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)

关于python - 如何在 python 中反转句子的部分内容?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39359599/

相关文章:

python - 使用 pandas GroupBy 聚合时设置 MultiIndex

python - 如何计算 SQL 行并使用 FLASK 将其存储在变量中,而不总是得到 1 作为答案?

python - 如何根据pandas中的两列合并多行

python - 使用python在保存的csv文件中打印列名

python - 如何使用 tkinter 在第二个窗口上创建 "go back Button"?

python - 如何在 PyTorch 中指定多个转换层后的展平层输入大小?

python - 根据组的频率计数添加新列

python - 如何获取 Pandas 数据帧每行中包含预定义等价类值名称的列?

python-3.x - 在线程中使用 psycopg2 游标的正确方法是什么?

python - 将负数、NaN 和 0 替换为下一个和上一个正数的平均值