程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

Python read Tsp type file

編輯:Python

I've been learning to use python Write optimization algorithm to solve tsp problem , Therefore, some .tsp Example of type , Such as :berbin8 etc. 、berlin52 etc. 、a208.tsp etc. , So how to use python Import .tsp What about the documents ? Record the problem briefly .

1. First look at it. berlin8.tsp The data format of the file , You can see , The first 7 The row begins to record the coordinates of the node , The last line is the end sign, which is useless , Basically, all numerical examples are in this format ;

2. Here I use pandas Import data , Pay attention to the need for Skip the first six lines without reading (skiprows=6)

df = pd.read_csv(r".\ Combinatorial optimization learning \demo_tsp\berlin8.tsp",sep=" ",skiprows=6,header=None,encoding='utf8')

Then read the nodes and coordinates , The code is as follows :

df = pd.read_csv(r".\ Combinatorial optimization learning \demo_tsp\berlin8.tsp",sep=" ",skiprows=6,header=None,encoding='utf8')
node=list(df[0][0:-1])
num_points=len(node)
city_x = np.array(df[1][0:-1])
city_y = np.array(df[2][0:-1])
points= list(zip(city_x, city_y))

Print the read node coordinates , It's a success , Next, you can write an algorithm to solve tsp Problem. .

 3. It's not over yet ,,,,, I used the same method to open berlin52.tsp When you file , Wrong report ! This sentence means reading the file 17 Look forward to when you go 3 A field , namely df There are three columns , But there are four fields , There is a problem with the field of the source file .

ParserError: Error tokenizing data. C error: Expected 3 fields in line 17, saw 4

4. I found many methods on the Internet, which are cumbersome and not necessarily useful , I used a simple and crude method . First set up error_bad_lines=False, Then when reading the file print Which lines are wrong? Skip directly and don't read , And the reason for the mistake .

df = pd.read_csv(r".\ Combinatorial optimization learning \demo_tsp\berlin52.tsp",sep=" ",skiprows=6,header=None,error_bad_lines=False)

result :

b'Skipping line 17: expected 3 fields, saw 4\nSkipping line 25: expected 3 fields, saw 5\n

The result shows that 17 Xing He 25 There are a few more characters in the line , Is a newline \n;

The easiest way is to open it directly .tsp file , find 17 and 25 That's ok , Delete the line , Just input it again and save it .

5. Then run the code in step 4 to reread without any error , Read all in .

 


  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved