2016-11-17 1 views
-1

지도에서 X, Y 좌표 및 플롯 수를 제공하는 코드로 작업 중입니다. 플롯 번호 20,21,22 등. 그러나지도에 20-A, 20A 또는 20과 같은 영숫자 값이있는 경우 A, 나는 20-A와 같은 값을 입력 할 때 "ValueError : base 10의 int()에 대한 리터럴이 잘못되었습니다."라는 오류가 발생합니다. 그래서 영숫자 값을 처리하는 방법을 알려주십시오.ValueError : 10 진수의 int()에 대한 리터럴이 잘못되었습니다. 영숫자 값을 수정하는 방법은 무엇입니까?

여기 내 코드입니다.

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() 
+0

이 일어날 무엇을 기대할 수 있습니까? 이것을 "20"정수로 변환 하시겠습니까? –

+0

아니요 정확한 값, 즉 "20-A"를 입력하고 싶지만 20-A를 입력하면 오류가 발생합니다. 이제 정수 만 입력 할 수 있고 정수와 영숫자 값을 모두 입력하고 싶습니다. – Zeeshan

+0

"20-A2"를 입력하면 어떻게됩니까? 어떤 숫자를 얻을 것으로 예상합니까? 20? 202? 20,2의 목록? –

답변

0

당신은 예를 들어,이 "20-A".split('-')['20','A']를 반환한다 (20) 및 A.

에 20-A를 구분하기 split 함수를 사용할 수있다. 그런 다음이 배열의 첫 번째 요소에서 int 메서드를 호출 할 수 있습니다.

+0

감사합니다. 내게이 기능을 사용하는 곳을 알려 주셔서 감사드립니다. 변경 사항을 적용하고 변경 사항을 적용한 코드를 얻으려면 작업 코드를 작성하십시오. – Zeeshan

0

일반적인 방법으로 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에 숫자 문자열을 변환하는 코드를 같이해야한다 : 값이 "20-A는"인 경우

number_string = get_number_from_string('20A')[0] # For getting only 1st number from list 
number = int(number_string) # Type-cast it to int  
+0

감사합니다. UR 응답을 받으려면 plz 코드를 변경하고 게시하십시오. – Zeeshan

+0

전체 코드를 확인하지 않았습니다. 나는 당신의 질문에 답했다 : * "20-A, 20A 또는 20A와 같은 영숫자 값을 가진 맵의 경우, 20-A와 같은 값을 입력하면 멈추게됩니다."* 당신의 코드입니다. 이것을 넣으십시오 :) –

관련 문제