【问题标题】:ValueError: invalid literal for int () with base 10. How to fix alphanumeric values?ValueError: int () 以 10 为底的无效文字。如何修复字母数字值?
【发布时间】:2016-11-17 06:00:15
【问题描述】:

我正在使用一个代码,该代码为我提供地图中的 X、Y 坐标和地块编号。例如:地块编号 20、21、22 等。但如果地图具有字母数字值,例如 20-A、20A 或20 A,我被卡住了,因为当我输入像 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()

【问题讨论】:

  • 如果值为“20-A”,您预计会发生什么?你想把它转换成整数“20”吗?
  • 不,我想输入确切的值,即“20-A”,但是当我输入 20-A 时出现错误。现在我只能输入整数,我想同时输入整数和字母数字值
  • 如果输入“20-A2”会怎样?你希望得到什么数字? 20? 202? 20,2 的列表?

标签: javascript python maps


【解决方案1】:

您可以使用split 函数将 20-A 分为 20 和 A。

例如,"20-A".split('-') 将返回 ['20','A']。然后你可以在这个数组的第一个元素上调用int方法

【讨论】:

  • 谢谢先生,您能告诉我在哪里使用此功能,因为我是新手,或者进行更改并让我获得更改后的代码。
【解决方案2】:

一般方法是使用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     

【讨论】:

  • 非常感谢您的回答,请您更改代码并发布。
  • 我还没有检查你的整个代码。我回答了你的问题:“但是如果地图有 20-A、20A 或 20 A 之类的字母数字值,我会卡住,因为当我输入 20-A 之类的值时” 这是你的代码,你知道把这个放在哪里:)
猜你喜欢
  • 2018-09-09
  • 2020-01-04
  • 2010-12-22
  • 2011-07-07
  • 2019-10-14
  • 2022-05-19
相关资源
最近更新 更多