Define "value type" from string in python

I am trying to write a function in python that will determine what type of value is in a string; eg

if line 1 or 0 or True or False is BIT

if line 0-9 *, value INT

if in line 0-9 + .0-9 + the value is float

if the string has more stg (text, etc.), the value is text

As long as I have stg like

def dataType(string):

 odp=''
 patternBIT=re.compile('[01]')
 patternINT=re.compile('[0-9]+')
 patternFLOAT=re.compile('[0-9]+\.[0-9]+')
 patternTEXT=re.compile('[a-zA-Z0-9]+')
 if patternTEXT.match(string):
     odp= "text"
 if patternFLOAT.match(string):
     odp= "FLOAT"
 if patternINT.match(string):
     odp= "INT"
 if patternBIT.match(string):
     odp= "BIT"

 return odp 

But I am not very good at using regular expressions in python. Could you tell me what I am doing wrong? For example, it does not work in 2010-00-10, which should be Text, but is INT or 20.90, which should be float, but int

+3
source share
4 answers

, ast.literal_eval

:

In [35]: ast.literal_eval('1')
Out[35]: 1

In [36]: type(ast.literal_eval('1'))
Out[36]: int

In [38]: type(ast.literal_eval('1.0'))
Out[38]: float

In [40]: type(ast.literal_eval('[1,2,3]'))
Out[40]: list

Python !

, :

import ast, re
def dataType(str):
    str=str.strip()
    if len(str) == 0: return 'BLANK'
    try:
        t=ast.literal_eval(str)

    except ValueError:
        return 'TEXT'
    except SyntaxError:
        return 'TEXT'

    else:
        if type(t) in [int, long, float, bool]:
            if t in set((True,False)):
                return 'BIT'
            if type(t) is int or type(t) is long:
                return 'INT'
            if type(t) is float:
                return 'FLOAT'
        else:
            return 'TEXT' 



testSet=['   1  ', ' 0 ', 'True', 'False',   #should all be BIT
         '12', '34l', '-3','03',              #should all be INT
         '1.2', '-20.4', '1e66', '35.','-   .2','-.2e6',      #should all be FLOAT
         '10-1', 'def', '10,2', '[1,2]','35.9.6','35..','.']

for t in testSet:
    print "{:10}:{}".format(t,dataType(t))

:

   1      :BIT
 0        :BIT
True      :BIT
False     :BIT
12        :INT
34l       :INT
-3        :INT
03        :INT
1.2       :FLOAT
-20.4     :FLOAT
1e66      :FLOAT
35.       :FLOAT
-   .2    :FLOAT
-.2e6     :FLOAT
10-1      :TEXT
def       :TEXT
10,2      :TEXT
[1,2]     :TEXT
35.9.6    :TEXT
35..      :TEXT
.         :TEXT

, , :

def regDataType(str):
    str=str.strip()
    if len(str) == 0: return 'BLANK'

    if re.match(r'True$|^False$|^0$|^1$', str):
        return 'BIT'
    if re.match(r'([-+]\s*)?\d+[lL]?$', str): 
        return 'INT'
    if re.match(r'([-+]\s*)?[1-9][0-9]*\.?[0-9]*([Ee][+-]?[0-9]+)?$', str): 
        return 'FLOAT'
    if re.match(r'([-+]\s*)?[0-9]*\.?[0-9][0-9]*([Ee][+-]?[0-9]+)?$', str): 
        return 'FLOAT'

    return 'TEXT' 

ast; Python , , , , ...

+12

json.

import json
converted_val = json.loads('32.45')
type(converted_val)

type <'float'>

:

re.match() , . , "2010-00-10" :

if patternTEXT.match(str_obj): #don't use 'string' as a variable name.

, odp ""

script :

if patternFLOAT.match(str_obj):

, odp - ""

if patternINT.match(str_obj):

odp "INT"

, if, , odp.

:

  • if, .

  • if elif if, .

  • , :

    ...
    match = patternINT.match(str_obj)
    if match:
        if match.end() == match.endpos:
            #do stuff
    ...
    
+4

, :

  • 2010-00-10 ( int, )
  • 20.90 ( int, float)

:

def dataType(string):

 odp=''
 patternBIT=re.compile('[01]')
 patternINT=re.compile('[0-9]+')
 patternFLOAT=re.compile('[0-9]+\.[0-9]+')
 patternTEXT=re.compile('[a-zA-Z0-9]+')
 if patternTEXT.match(string):
     odp= "text"
 if patternFLOAT.match(string):
     odp= "FLOAT"
 if patternINT.match(string):
     odp= "INT"
 if patternBIT.match(string):
     odp= "BIT"

 return odp 

if - :

if patternTEXT.match(string):
    odp= "text"
if patternFLOAT.match(string):
    odp= "FLOAT"
if patternINT.match(string)
    odp= "INT"
if patternBIT.match(string):
    odp= "BIT"

"2010-00-10" , float (, .), int, , [0-9]+.

:

if patternTEXT.match(string):
    odp = "text"
elif patternFLOAT.match(string):
    ...

, , , , , , , int ( ). , "text" - , .

, AST:

def get_type(string):

    if len(string) == 1 and string in ['0', '1']:
        return "BIT"

    # int has to come before float, because integers can be
    # floats.
    try:
        long(string)
        return "INT"
    except ValueError, ve:
        pass

    try:
        float(string)
        return "FLOAT"
    except ValueError, ve:
        pass

    return "TEXT"

:

In [27]: get_type("034")
Out[27]: 'INT'

In [28]: get_type("3-4")
Out[28]: 'TEXT'


In [29]: get_type("20.90")
Out[29]: 'FLOAT'

In [30]: get_type("u09pweur909ru20")
Out[30]: 'TEXT'
+2

For example, it does not work in 2010-00-10, which should be Text, but it is INT or 20.90, which should be float, but int

>>> import re
>>> patternINT=re.compile('[0-9]+')
>>> print patternINT.match('2010-00-10')
<_sre.SRE_Match object at 0x7fa17bc69850>
>>> patternINT=re.compile('[0-9]+$')
>>> print patternINT.match('2010-00-10')
None
>>> print patternINT.match('2010')
<_sre.SRE_Match object at 0x7fa17bc69850>

Remember $to limit the end of the line.

+1
source

All Articles