re.sub python收集高度

Vik*_*k G 3 python regex string parsing

我正在编写一个python程序来解析txt文件中的一些用户数据.文本文件中的一行将包含用户的高度.我已经指定了用户希望遵循的订单

文件的第一行应包含名称,下一行,出生日期,第3行,高度等.

我还给用户一个示例文件,看起来像这样

姓名:名字姓氏
DOB
:16.04.2000年龄:16
身高:5英尺9英寸

当我读取文件时,我查看了每一行并使用':'作为分隔符将其拆分.

第一个字段是我的列名,如name,dob,age,height.

在某些情况下,用户会在Name或DOB之后忘记':',或者他们只会发送如下数据:

  • 身高5英尺9英寸
  • 5英尺9英寸
  • 5英尺9英寸
  • 5英尺9英寸

我决定使用的逻辑是:

  1. 在每一行上寻找':'; 如果找到一个,那么我有我的领域.
  2. 否则,尝试找出它可能是什么数据.

高度的逻辑是这样的:

if any(heightword in file_line.upper() for heightword in ['FT', 'HEIGHT', 'FEET', 'INCH', 'CM'])
Run Code Online (Sandbox Code Playgroud)

if条件将查找与高度相关的单词.

一旦我确定文件中的行包含高度,我希望能够在将其写入数据库之前将该信息转换为英寸.

请有人帮我解决如何将以下数据转换为英寸.

  • 身高5英尺9英寸
  • 5英尺9英寸
  • 5英尺9英寸
  • 5英尺9英寸

我知道,因为我正在尝试迎合各种用户输入.这份清单并非详尽无遗; 我试图用这些作为一个例子来理解,然后我将继续添加代码,如果我找到新的模式.

Pau*_*McG 5

对于像这样的简单解析情况,pyparsing是一个很好的模块,特别是在尝试处理低于可预测但仍然相当结构的人类输入时.你可以使用一些友好命名类组成解析器(Keyword,Optional,OneOrMore,等)和算术运算符('+'用于序列,'|'替代品等),装配更小的解析器成大.这是一个由你的例子中的位构建的解析器(也支持'和'用于英尺和英寸,以及小数英尺和英寸值).(此示例使用最新版本的pyparsing,版本2.1.4):

samples = """\
Height 5 feet 9 inch
5 feet 9 inch
5ft 9 in
5feet 9inches
5'-9-1/2"
5' 9-1/2"
5' 9 1/2"
6'
3/4"
3ft-6-1/4 in
"""


from pyparsing import CaselessKeyword, pyparsing_common, Optional

CK = CaselessKeyword
feet_units = CK("feet") | CK("ft") | "'"
inch_units = CK("inches") | CK("inch") | CK("in") | '"'

# pyparsing_common.number will parse an integer or real, and convert to float
integer = pyparsing_common.number

fraction = integer + '/' + integer
fraction.addParseAction(lambda t: t[0]/t[-1])

qty = fraction | (integer + Optional(fraction)).addParseAction(lambda t:sum(t))

# define whole Height feet-inches expression
HEIGHT = CK("height") | CK("ht")
inch_qty = qty("inches")
feet_qty = qty("feet")
height_parser = Optional(HEIGHT) + (inch_qty + inch_units | 
                                feet_qty + feet_units + Optional(inch_qty + inch_units))

# use parse-time callback to convert feet-and-inches to inches
height_parser.addParseAction(lambda t: t.get("feet", 0.0)*12 + t.get("inches", 0.0))

height_parser.ignore("-")

height_parser.runTests(samples)

# how to use the parser in normal code
height_value = height_parser.parseString(samples.splitlines()[0])[0]
print(height_value, type(height_value))
Run Code Online (Sandbox Code Playgroud)

打印:

Height 5 feet 9 inch
[69.0]


5 feet 9 inch
[69.0]


5ft 9 in
[69.0]


5feet 9inches
[69.0]


5'-9-1/2"
[69.5]


5' 9-1/2"
[69.5]


5' 9 1/2"
[69.5]


6'
[72.0]


3/4"
[0.75]


3ft-6-1/4 in
[42.25]

69.0 <type 'float'>
Run Code Online (Sandbox Code Playgroud)