【问题标题】:Preprocessing numbers in Python在 Python 中预处理数字
【发布时间】:2018-05-31 11:52:21
【问题描述】:

在预处理数据时,我将获得具有不同格式的相同数字特征。 例如:

1x4 wire       1 x 4 wire
1-1/2x1 wire   1-1/2 x 1 wire
11/2x1 wire    1-1/2 x 1 wire 

我需要将不同的格式标准化为一种格式。

我们认为的一种方法是删除 x、-、/ 和空格并将所有内容组合在一起。 即:

1x4 wire       1 x 4 wire         14 wire
1-1/2x1 wire   1-1/2 x 1 wire     1121 wire
11/2x1 wire    1-1/2 x 1 wire     1121 wire

谁能告诉如何在 Python 中实现上述方法?

我尝试了以下代码来匹配所需的模式:

import re
regex = re.compile('(\d+.*?)\s?')

我不知道如何将其输出用于re.sub

【问题讨论】:

  • 1.学习 Python。 2.用Python编写代码。

标签: regex python-3.x regex-group


【解决方案1】:

这是使用re.sub 删除任何字符 x、- 或 / 的两种方法,如果空格位于数字字符之前和之后,则空格位于其前后:

import re

myText = """
            1-1/2x1 wire cross box
            1x4 wire       1 x 4 wire         14 wire
            1-1/2x1 wire   1-1/2 x 1 wire     1121 wire
            11/2x1 wire    1-1/2 x 1 wire     1121 wire
        """

# First way
myNewText1 =  re.sub(r'(?<=([0-9])) *[x\-\/] *(?=([0-9]))', '', myText)
print(myNewText1)

# Second way (by defining first a regex pattern)
myPattern = re.compile(r'(?<=([0-9])) *[x\-\/] *(?=([0-9]))')
myNewText2 =  myPattern.sub('', myText)
print(myNewText2)

两者都打印以下结果:

1121 wire cross box
14 wire       14 wire         14 wire
1121 wire   1121 wire     1121 wire
1121 wire    1121 wire     1121 wire

【讨论】:

  • 非常感谢您的回复。如果我的输入是f="1-1/2x1 wire cross box",那么我会得到myNewText1 = re.sub(r' *[x\-\/] *', '', f)print(myNewText1)1121 wire cross bo。我只需要在带有数字时删除。 `
猜你喜欢
  • 2016-08-03
  • 2018-07-28
  • 2022-12-21
  • 1970-01-01
  • 1970-01-01
  • 2021-07-31
  • 2011-01-22
  • 2019-09-21
  • 2015-10-07
相关资源
最近更新 更多