ValueError:以10为基数的int()无效文字.如何固定字母数字值
ValueError: invalid literal for int () with base 10. How to fix alphanumeric values?
我正在使用一个代码,它给了我X,Y坐标和地图中的plot数字。例如:20号、21号、22号地块等。但是如果映射有像20-A,20A或20A这样的字母数字值,我就会卡住,因为当我输入像20-A这样的值时,我会得到这个错误"ValueError:无效的int()以10为基数"。所以请告诉我如何处理字母数字值。
这是我的代码。
import matplotlib.pyplot as plt
from PIL import Image
import numpy as np
import Tkinter as tk
import tkSimpleDialog
#Add path of map file here. The output will be saved in the same path with name map_file_name.extension.csv
path = "maps/21.jpg"
#Set this to true for verbose output in the console
debug = False
#Window for pop ups
root = tk.Tk()
root.withdraw()
root.lift()
root.attributes('-topmost',True)
root.after_idle(root.attributes,'-topmost',False)
#Global and state variables
global_state = 1
xcord_1, ycord_1, xcord_2, ycord_2 = -1,-1,-1,-1
edge1, edge2 = -1,-1
#Defining Plot
img = Image.open(path)
img = img.convert('RGB')
img = np.array(img)
if(debug):
print "Image Loaded; dimensions = "
print img.shape
#This let us bind the mouse function the plot
ax = plt.gca()
ax.axes.get_xaxis().set_visible(False)
ax.axes.get_yaxis().set_visible(False)
fig = plt.gcf()
#Selecting tight layout
fig.tight_layout()
#Plotting Image
imgplot = ax.imshow(img)
#Event listener + State changer
def onclick(event):
global xcord_1,xcord_2,ycord_1,ycord_2,edge1,edge2, imgplot,fig, ax, path
if(debug):
print "Single Click Detected"
print "State = " + str(global_state)
if event.dblclick:
if(debug):
print "Double Click Detection"
global global_state
if(global_state==0):
xcord_1 = event.xdata
ycord_1 = event.ydata
edge1 = (tkSimpleDialog.askstring("2nd", "No of 2nd Selected Plot"))
#Draw here
if edge1 is None: #Incase user cancels the pop up. Go to initial state
global_state = 1
pass
else:
edge1 = int(edge1)
global_state = 1
difference = edge2-edge1
dif_state = 1;
#So difference is always positive. Dif_state keeps track of plot at which side has the larger number
if difference <0:
dif_state = -1;
difference *= -1
#Corner Case; labelling a single plot
if(difference == 0):
import csv
fields = [int(xcord_1),int(ycord_1),edge1]
plt.scatter(int(xcord_1),int(ycord_1),marker='$' + str(edge1) + '$', s=150)
with open(path+'.csv', 'a') as f:
writer = csv.writer(f)
writer.writerow(fields)
else:
if(debug):
print "P1 : (" + str(xcord_1) + ", " + str(ycord_1) + " )"
print "P2 : (" + str(xcord_2) + ", " + str(ycord_2) + " )"
for a in range(0,difference+1):
#Plotting the labels
plt.scatter(int(xcord_1+(a*(float(xcord_2-xcord_1)/difference))),int(ycord_1+a*((float(ycord_2-ycord_1)/difference))),marker='$'+str(edge1+dif_state*a)+'$',s=150)
#Saving in CSV
import csv
fields = [int(xcord_1+(a*(float(xcord_2-xcord_1)/difference))),int(ycord_1+a*((float(ycord_2-ycord_1)/difference))),str(edge1+dif_state*a)]
with open(path+'.csv', 'a') as f:
writer = csv.writer(f)
writer.writerow(fields)
if debug:
print (int(xcord_1+(a*(float(xcord_2-xcord_1)/difference))),int(ycord_1+a*((float(ycord_2-ycord_1)/difference))))
plt.show()
elif(global_state == 1):
xcord_2 = event.xdata
ycord_2 = event.ydata
print "Recorded"
edge2 = (tkSimpleDialog.askstring("1st", "No of Selected Plot"))
print type(edge2)
if edge2 is None:
root.withdraw()
pass
else:
edge2 = int(edge2)
global_state = 0
cid = fig.canvas.mpl_connect('button_press_event', onclick)
plt.show()
您可以使用split
函数将20- a分离为20和a。
例如,"20-A".split('-')
将返回['20','A']
。然后,您可以在此数组的第一个元素上调用int
方法
一般的方法是使用regex
从文本中提取数字。
import re
def get_number_from_string(my_str):
return re.findall(''d+', my_str)
这将从字符串中提取所有数字并返回list
。
如果您只需要一个值,则提取索引0
处的数字。示例运行:
>>> get_number_from_string('20-A')
['20']
>>> get_number_from_string('20 A')
['20']
>>> get_number_from_string('20A')
['20']
因此,将数字字符串转换为int
的代码应该如下:
number_string = get_number_from_string('20A')[0] # For getting only 1st number from list
number = int(number_string) # Type-cast it to int
相关文章:
- 添加文字和评论功能更新Div
- 如果我在javascript中输入无效的电子邮件或空白,如何显示特定的文本框边框红色
- jquery代码在Mozilla中有效,但在其他浏览器上无效
- 如何计算对象文字中的键
- I'我想放下画布上的文字.帮帮我
- 这个问号在Flow中意味着什么:“;?()=>“无效”;
- 从字符串末尾删除空白无效
- Jquery Datatables错误:无效的JSON基元:draw
- 对象文字方法上的Javascript绑定不起作用
- 滚动在Chrome中有效,但在Firefox或IE中无效
- 以ECMAScript 5及更高版本为目标时,八进制文字不可用
- 错误:语法错误,无法识别的表达式:不支持的伪:无效/RectJS/Unit Testing
- ES6 模板文字是否比 eval 更安全
- Javascript setattribute-名称和值无效
- 格式化货币无效
- JavaScript错误无效的限定符
- 按键事件无效的原因
- Laravel数据表无效的JSON响应
- ValueError:以10为基数的int()无效文字.如何固定字母数字值
- 当将整数值从表单传递到Javascript函数时,无效的文字错误