【问题标题】:Split a string at uppercase letters, but only if a lowercase letter follows in Python [closed]以大写字母拆分字符串,但前提是在 Python 中跟随小写字母 [关闭]
【发布时间】:2020-11-15 10:10:25
【问题描述】:

我在 Python 中使用 pdfminer.six 来提取长文本数据。不幸的是,Miner 并不总是能很好地工作,尤其是在段落和文本换行方面。例如我得到以下输出:

"2018Annual ReportInvesting for Growth and Market LeadershipOur CEO will provide you with all further details below."

--> "2018 Annual Report Investing for Growth and Market Leadership Our CEO will provide you with all further details below."

现在我想在小写字母后跟一个大写字母然后是一个小写字母(以及数字)时插入一个空格。所以最后"2018Annual"变成"2018 Annual""ReportInvesting"变成"Report Investing",但是"...CEO..."仍然是"...CEO..."

我只找到了Split a string at uppercase lettershttps://stackoverflow.com/a/3216204/14635557 的解决方案,但无法重写。不幸的是,我是 Python 领域的新手。

【问题讨论】:

  • 即使是 Python 编码新手,您仍然应该尝试一些编码并在寻求解决方案之前发布您尝试过的内容
  • 明白了,下次会努力改进的

标签: python split text-mining uppercase


【解决方案1】:

我们可以在这里尝试使用re.sub 进行正则表达式方法:

inp = "2018Annual ReportInvesting for Growth and Market LeadershipOur CEO will provide you with all further details below."
inp = re.sub(r'(?<![A-Z\W])(?=[A-Z])', ' ', inp)
print(inp)

打印出来:

2018 Annual Report Investing for Growth and Market Leadership Our CEO will provide you with all further details below.

这里使用的正则表达式表示在任何点插入一个空格:

(?<![A-Z\W])  what precedes is a word character EXCEPT
              for capital letters
(?=[A-Z])     and what follows is a capital letter

【讨论】:

    【解决方案2】:

    尝试用正则表达式分割:

    import re
    temp = re.sub(r"([A-Z][a-z]+)", r"\1", string).split()
    
    string = ' '.join(temp)
    

    【讨论】:

      【解决方案3】:

      我相信下面的代码给出了所需的结果。

      temp = re.sub(r"([a-z])([A-Z])", r"\1 \2", text)
      temp = re.sub(r"(\d)([A-Za-z])", r"\1 \2", temp)
      

      我仍然觉得复杂的正则表达式有点挑战性,因此需要将过程分成两个表达式。 也许更擅长正则表达式的人可以对此进行改进,以展示如何以更优雅的方式实现它。

      【讨论】:

        猜你喜欢
        • 2019-08-08
        • 2014-02-06
        • 2018-05-10
        • 2021-01-06
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-01-28
        相关资源
        最近更新 更多