Python Script in ArcGIS 10 is using module re and is returning “global name 're' is not defined”

StackOverflow https://stackoverflow.com/questions/12733539

문제

I am new to python scripting and I mainly use it in ArcGIS 10. My script is supposed to reformat a string within the Field CINTP1. An example would be '000000100' and return '1.00'. I have imported it into a toolbox to run on a selected record within the table 'MAPCHAR'. The error I keep recieveing is:

: ERROR 000539: Error running expression: removeLeadingZeros("000000100") : global name 're' is not defined Failed to execute (CalculateField).

Failed to execute (Script).

Here is my script:

import arcpy, re, sys, string, os

MAPCHAR = "MAPCHAR"

CINPT1 = "CINPT1"

expression = "removeLeadingZeros(!CINPT1!)"
codeblock = """def removeLeadingZeros(myValue):
    newValue = re.sub('^0+',"",myValue)

    valueList = list(newValue) #convert newValue to List
    valueList.insert(-2, '.') #insert the '.' characater int the list at the -2 position

    newValue = "".join(valueList) #join back to create the new  updated string

    myvalue = newValue"""

arcpy.CalculateField_management(MAPCHAR, CINPT1, expression, "Python", codeblock)

Any help would be appreciated..thanks,

도움이 되었습니까?

해결책

You should have your import statements in the below codeblock.. So add an import re as the first line in codeblock: -

codeblock = """import re
    def removeLeadingZeros(myValue):
        newValue = re.sub('^0+',"",myValue)

        valueList = list(newValue) #convert newValue to List
        valueList.insert(-2, '.') #insert the '.' int the list at the -2 position

        newValue = "".join(valueList) #join back to create the new  updated string

        myvalue = newValue"""

다른 팁

It looks like you're running codeblock in the arcpy namespace. If arcpy doesn't have import re in it, codeblock wont work.

incidentally, you dont need regex to remove leading zeros-- just convert to an int. Classic example of using a wrench to hammer a nail.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top