【问题标题】:Substituting a specific character at the end of words在单词末尾替换特定字符
【发布时间】:2021-09-30 06:41:01
【问题描述】:
import re

text="Her sweet-natured father is constantly henpecked by his domineering wives, who rule their domains with iron fists. His wives were named Alexis, Eris, Irer, Zenith and Saunder."
text=re.sub(r'r$\b','rh',text)
print(text)

期望的输出:

她和蔼可亲的父亲总是被他的霸道吓到 妻子,用铁腕统治他们的领域。他的妻子被命名为 Alexis、Eris、Irerh、Zenith 和 Saunderh。

输出:

她和蔼可亲的父亲总是被他的霸道吓到 妻子,他们用铁腕统治他们的领域。他的妻子被命名为 Alexis、Eris、Irer、Zenith 和 Saunder。

即,字符串中没有发生任何变化。有什么问题吗?

【问题讨论】:

  • 为什么"Her" 在您想要的输出中不受影响?
  • 测试你的正则表达式,例如regex101.com,从描述上应该问题很明显了。
  • 这里也不适合使用正则表达式。这是家庭作业吗?
  • $ 在正则表达式中做了什么?
  • @ddejohn 这是我正在进行的项目的一部分,而不是家庭作业

标签: python regex python-re


【解决方案1】:
  1. white spacespunctutations分割文本。
  2. 检查所有部分,最后一个字符是否为r
  3. 如果等于r,则在该部分添加一个字符h
  4. 将所有部分连接在一起。

检查下面的代码:

import re
text="Her sweet-natured father is constantly henpecked by his domineering wives, who rule their domains with iron fists. His wives were named Alexis, Eris, Irer, Zenith and Saunder."
parts = re.split("([\.\,\!\?\-\s+\_])", text)
for index, part in enumerate(parts):
    if len(part) != 0 and part[-1] == 'r':
       parts[index] += 'h'
final_text = "".join(parts[:])
print(final_text)

结果
赫赫和蔼可亲的父亲经常被他霸道的妻子们嫌弃,他们用铁腕统治着他们的领域。他的妻子叫 Alexis、Eris、Irerh、Zenith 和 Saunderh。

【讨论】:

  • 其实我只想替换词尾的r,而不是句子中的所有r。
  • 我知道,我的代码也在这样做。它用rhs 后跟一个空格替换后面有一个空格的r s。试试我的代码。它有效。
  • 它不符合 OP 的要求。例如,您缺少单词结尾后跟,. 的实例。这个解决方案有太多的边缘案例不实用。
  • @MsBonniePython ,我更新了答案。请检查一下。
  • @ddejohn ,我更新了我的答案。请检查一下。
【解决方案2】:

你可以使用 str.replace 和 \b:

text.replace(r'r\b',r'rh')

\b 匹配单词边界:即单词的开头 (\W\w) 或单词的结尾 (\w\W)。所以r\b 捕获任何单词末尾的任何“r”。

text="Her sweet-natured father is constantly henpecked by his domineering wives, who rule their domains with iron fists. His wives were named Alexis, Eris, Irer, Zenith and Saunder."
result="Herh sweet-natured fatherh is constantly henpecked by his domineering wives, who rule theirh domains with iron fists. His wives were named Alexis, Eris, Irerh, Zenith and Saunderh."

【讨论】:

    猜你喜欢
    • 2021-02-19
    • 1970-01-01
    • 2020-11-04
    • 2012-02-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多