识别整数、字符串和浮点数字面量

3

我是新手Python程序员,遇到了一个问题。我的输入文件包含以下数据:

12345    67890     afghe
abcde    23456     0abcd
34567    __fred01  45678
123.456  12345a    123.
.456     ab00cd    00ab00

使用正则表达式需要解析每个字面量并分类,确定该字面量是字符串、整数还是浮点数。 代码片段如下:

def processtoken(token):
    #Replace the following line with your code to classify
    # the string in 'token' according to your three Regular
    # Expressions and print the appropriate message.
    print('Inside Process Token')

    match = re.search(r'(0|[1-9][0-9]*|0[oO]?[0-7]+|0[xX][0-9a-fA-F]+|0[bB][01]+)[lL]?', token)
    matchfp = re.search(r'^[0-9]+\.?[0-9]+$',token)
    if match:
        print(match.group(),'matches INT')
    elif matchfp:
        print(matchfp.group(),'matches FP')

我的问题是如何构建代码以验证每个传递的标记的多个正则表达式条件。目前,如果该条件未经验证,则浮点数将不符合条件。我想检查标记,首先是整数正则表达式是否匹配,如果匹配或者它匹配浮点数正则表达式或字符串正则表达式。

任何帮助都将不胜感激。


如果您坚持使用正则表达式来匹配数字字面量,请参阅文档以获取完整列表 - https://docs.python.org/3/reference/lexical_analysis.html#numeric-literals - Sundeep
3个回答

1

我会将问题结构化如下:

integer_regex = r"^...$"
float_regex = r"^...$"
string_regex = r"^...$"

def processToken(token):

    if re.search(integer_regex, token):
        print(token, 'matches INT')
    elif re.search(float_regex, token):
        print(token, 'matches FLOAT')
    elif re.search(string_regex, token):
        print(token, 'matches STR')
    else:
        print(token, 'unknown')

将您的模式填入上面的*_regex变量中。
此外,请注意,您的float模式不好,因为它还匹配了int
r'^[0-9]+\.?[0-9]+$'

由于小数点是可选的。您最好将模式分成三个选项的交替,以'.'开头,以'.'结尾或在数字之间包含'.'。另外,在您的整数模式中,八进制部分的'?'是不正确的:

0[oO]?[0-7]+

目前我们正试图提交八进制,因此前缀不是可选项:

0[oO][0-7]+

你已正确完成了十六进制和二进制。


请问您能帮忙吗? - np05
@np05,你在匹配模式时忘记了起始和结束锚点,这在使用r"^...$"方式匹配时是必需的。另外,你的字符串模式缺少括号:r"^(|[a-z]|[A-Z])(|[a-z]|[A-Z]|[0-9])*$"。目前定义的模式不匹配"0abcd",因为你说字符串不能以数字开头,也没有"0a"这样的整数形式。你的浮点数模式接近正确,但还需要一些改进。请按照我刚才提出的更改来进行修改,并查看仍然无法匹配的内容。 - cdlane
非常感谢您的输入。我将以下输出粘贴如下:正在处理来自inputdata.txt的令牌... 12345匹配INT 67890匹配INT afghe不匹配 abcde不匹配 23456匹配INT 0abcd匹配INT 34567匹配INT __fred01匹配INT 45678匹配INT 123.456匹配INT 12345a匹配INT 123.匹配INT .456匹配INT ab00cd匹配INT 00ab00匹配INT,代码如下: - np05
导入re 导入sys integer_regex = r"^(0|[1-9][0-9]|0[oO][0-7]+|0[xX][0-9a-fA-F]+|0[bB][01]+)[lL]?$" #integer_regex = r"(0|[1-9][0-9])" floating_regex = r"[+-]?(\d+(.\d*)?|.\d+)([eE][+-]?\d+)?" string_regex = r"^(|a-z|A-Z)(|a-z|A-Z|0-9)*$" def processtoken(token): if re.search(integer_regex, token): print(token,'匹配 INT') elif re.search(floating_regex, token): print(token,'匹配 FP') elif re.search(string_regex, token): print(token,'匹配 ID') else: print(token,'不匹配') - np05
@np05,你的正则表达式仍然存在错误,我已经指出了,但你没有修复。而且你还因为没有好的理由引入了新的错误。退一步,放慢速度,仔细阅读你的正则表达式,并确保它们在语法和逻辑上都是正确的。你离一个可行的解决方案非常接近了。 - cdlane
显示剩余6条评论

1

将文本分割,使用函数 isdigit() 测试是否为 int,然后使用 try 测试是否为 float,并捕获 ValueError 以处理 string

for m in string.split():
    if m.isdigit():
        print(m, 'Int')
    else:
        try:
            float(m)
            print(m, 'Float')
        except ValueError:
            print(m, 'STR')

输出:

('12345', 'Int')('67890', 'Int')('afghe', 'STR')('abcde', 'STR')('23456', 'Int')('0abcd', 'STR')('34567', 'Int')('__fred01', 'STR')('45678', 'Int')('123.456', 'Float')('12345a', 'STR')('123.', 'Float')('.456', 'Float')('ab00cd', 'STR')('00ab00', 'STR')

代码演示


谢谢您的回答。但我必须只使用正则表达式来实现这个。 - np05

0
>>> test = """\
... 12345    67890     afghe
... abcde    23456     0abcd
... 34567    __fred01  45678
... 123.456  12345a    123.
... .456     ab00cd    00ab00"""
>>> def what_is_it(s):
...     print("'{}'".format(s), end=' ')
...     try:
...         as_float = float(s)
...     except ValueError:
...         return 'matches STRING'
...     else:
...         if as_float.is_integer():
...             return 'matches INT'
...         return 'matches FP'
... 
>>> for line in test.splitlines():
...     for token in line.split():
...         print(what_is_it(token))
...     print()
... 
'12345' matches INT
'67890' matches INT
'afghe' matches STRING

'abcde' matches STRING
'23456' matches INT
'0abcd' matches STRING

'34567' matches INT
'__fred01' matches STRING
'45678' matches INT

'123.456' matches FP
'12345a' matches STRING
'123.' matches INT

'.456' matches FP
'ab00cd' matches STRING
'00ab00' matches STRING

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接