2012-10-04 21 views
1

我是新來的Python腳本,我主要用它在ArcGIS 10.我的腳本應該重新格式化內的一個字符串字段CINTP1。一個例子是'000000100'並返回'1.00'。我已經將它導入到工具箱中,以在表格'MAPCHAR'內的選定記錄上運行。我一直recieveing的錯誤是:的Python腳本在ArcGIS 10是使用模塊重新並返回「沒有定義的全局名稱‘重’」

:ERROR 000539:錯誤運行表達式:removeLeadingZeros( 「000000100」):全球名稱 '重' 沒有定義 無法執行(CalculateField)。

無法執行(腳本)。

這裏是我的腳本:

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) 

任何幫助將是appreciated..thanks,

+3

我認爲你需要import語句添加到您的字符串'codeblock' .. –

回答

1

您應該具有下面的代碼塊import語句。所以添加import re在代碼塊的第一行: -

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""" 
+0

感謝您的快速響應!我在代碼塊中添加了import語句,但是現在我得到的錯誤是「name'newValue'沒有定義,我認爲它是在codeblock中用re.sub語句定義的。這,謝謝! – user1714326

+0

嘗試re.sub'語句後'打印'newValue',看看它打印.. –

+0

好吧...我發現這個問題。我有一個錯字(myvalue的= NEWVALUE應該myvalue的),但現在當我在ArcGIS執行該腳本,它返回一個空值到字段中。 – user1714326

0

它看起來像你運行在ArcPy中的命名空間codeblock。如果arcpy沒有import recodeblock將無法​​正常工作。

順便說一句,你不需要正則表達式來刪除前導zeros--只是轉換爲int。使用扳手敲擊指甲的經典例子。

+0

我還加了一個「。」到字符串。如果你有一些更簡單的方法來做到這一點,我肯定會考慮它。看起來,初學Python腳本需要很多錘子! – user1714326

+0

你可以在字符串中的任意一點插入'.'。 'string [: - 2] +「。」 + string [-2:]'在第二個字符之前插入'.'。 – kreativitea

相關問題