【问题标题】:How to replace hyphen and newline in string in Python如何在 Python 中替换字符串中的连字符和换行符
【发布时间】:2020-10-06 03:46:24
【问题描述】:

我正在处理具有多个音节划分的文本。

一个典型的字符串是这样的

"this good pe-
riod has"

我试过了:

my_string.replace('-'+"\r","")

但是,它不起作用。

我想得到

"this good period has"

【问题讨论】:

  • 我的回答对你有用吗?

标签: python-3.x regex nlp


【解决方案1】:

这取决于你的字符串如何结束,你也可以使用 my_string.replace('-\r\n', '') 或使用 re.sub 和 -(?:\r?\n|\r) 的可选回车

如果之前和之后必须有一个单词字符,而不是删除行尾的所有连字符,您可以使用环视:

(?<=\w)-\r?\n(?=\w)

Regex demo | Python demo

例如

import re

regex = r"(?<=\w)-\r?\n(?=\w)"
my_string = """this good pe-
riod has"""

print (re.sub(regex, "", my_string))

输出

this good period has

【讨论】:

  • @CarySwoveland 你很敏锐。 (我今天想说,但你总是很敏锐:-))
  • @CarySwoveland 是的,这就是为什么我以It depends how your string ends 开头的答案,比如ideone.com/Qkmu32
【解决方案2】:

匹配-后,应该匹配换行符\n

my_string = """this good pe-
riod has"""
print(my_string.replace("-\n",""))
# this good period has

【讨论】:

    【解决方案3】:

    你试过了吗?

    import re
    
    text = """this good pe-
    riod has"""
    print(re.sub(r"-\s+", '', text))
    # this good period has
    

    【讨论】:

      猜你喜欢
      • 2015-10-14
      • 2010-09-27
      • 2019-10-01
      • 2021-09-26
      • 1970-01-01
      • 2011-07-25
      • 1970-01-01
      • 2016-08-03
      • 2022-01-03
      相关资源
      最近更新 更多