【问题标题】:How to remove substrings "- " from a string in python, but keeping " - " substring?如何从python中的字符串中删除子字符串“-”,但保留“-”子字符串?
【发布时间】:2020-06-13 09:39:51
【问题描述】:

例子:

string = " a lot of text ... protective equip- ment ... a lot of text - with similar broken words like simple appli- cations ..."

我需要获得相同的文本,但 设备 变成 设备应用程序 变成 应用程序。 谢谢

【问题讨论】:

    标签: python-3.x string replace nlp str-replace


    【解决方案1】:

    一个需要连字符后跟空格的正则表达式,但如果它前面有空格则拒绝它,这样就可以了:

    import re
    string = "a lot of text ... protective equip- ment ... a lot of text - with similar broken words like simple appli- cations ..."
    print(re.sub(r"(?<! )- ", "", string))
    

    哪个输出:

    a lot of text ... protective equipment ... a lot of text - with similar broken words like simple applications ...
    

    【讨论】:

      【解决方案2】:

      如果您想删除两个单词之间的'- ',可以使用以下正则表达式:

      >>> import re
      >>> string = " a lot of text ... protective equip- ment ... a lot of text - with similar broken words like simple appli- cations ..."
      >>> re.sub(r"(\w+)- (\w+)", r"\1\2", string)
      ' a lot of text ... protective equipment ... a lot of text - with similar broken words like simple applications ...'
      

      【讨论】:

      • 我能知道为什么我被否决了吗?这个答案有什么问题?
      • 如果答案包含对代码的作用以及它如何解决问题的解释会更有帮助。
      • 您无需等到下次,您仍然可以编辑此答案。
      • 好的,希望现在好多了。
      • @Asocia,谢谢。我会尝试,两种解决方案。在这篇文章中,我只想让你知道,世界上有很多沮丧的人。他们“治愈”他们在现实生活中无法或不知道如何解决的挫败感、情结和问题,方法是对不适合他们狭小、封闭和有限盒子的任何人进行低调。我曾经对下注感到震惊,但现在我不在乎。我事先就知道他们会贬低我,但我不愿意遵循他们有限而愚蠢的思维规则。
      猜你喜欢
      • 1970-01-01
      • 2019-09-08
      • 1970-01-01
      • 2016-10-21
      • 2011-10-15
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多