【问题标题】:How to remove whitespaces in numerical values in a text file in python?如何删除python文本文件中数值中的空格?
【发布时间】:2021-06-22 14:19:28
【问题描述】:

我有一个大文本文件作为几个图像文档的 OCR 输出,它在数字部分的中间包含空格,例如“70 000 vs 100 000 NaCl”或“8 个区域42 孔”。我想删除这些空格并将它们替换为原始形式:70000、100000 或 842。我还有另一种形式的信息,例如“wells 14 29a 3”,它是井 ID 的正确形式,我不想要它们改变或连接。有人可以帮我解决这个问题吗?

例如下面的句子:

'offset wells 14 29a 3, 14 286c 2 and 20 46 C and the value of 70 000 vs 100 000'

我想要这样的输出:

'offset wells 14 29a 3, 14 286c 2 and 20 46 C and the value of 70000 vs 100000'

【问题讨论】:

  • 感谢您的链接。它删除了数字中的空格,但它也删除了这种模式的空间,因为它们是带空格的 id。比如“well 14 29a 3”会变成“well 1429a3”

标签: python regex string text data-cleaning


【解决方案1】:

您可以将re.sub 与用于检查尾随空格或行尾作为第二个数字组件的匹配条件的表达式一起使用。此外,可以使用自定义替换功能来确保匹配包括数字组,如果空格被逗号替换,这些数字组将形成有效的数值。这可确保 20 46 等匹配项不会变为 2046,因为 20,46 不是有效表达式:

import re
s = 'offset wells 14 29a 3, 14 286c 2 and 20 46 C and the value of 70 000 vs 100 000'
def s_repl(s):
   f = ''.join(d:=re.findall('\d+', (_d:=s.group())))
   if all((int(f) >= 1000 and len(i) == 3) or (len(i) == len(f) - 1) for i in d[1:]):
      return ''.join(re.split('(?<=\d)\s(?=\d)', _d))
   return _d
   
new_s = re.sub('(?:\s|^)\d+\s\d+(?:\s|$)', s_repl, s)

输出:

'offset wells 14 29a 3, 14 286c 2 and 20 46 C and the value of 70000 vs 100000'

【讨论】:

    猜你喜欢
    • 2013-08-25
    • 2021-07-29
    • 2019-05-18
    • 2015-04-11
    • 2017-11-03
    • 2013-08-29
    • 1970-01-01
    • 2011-04-27
    • 2014-08-07
    相关资源
    最近更新 更多