2017-06-27 16 views
1

的CSV例如,创建代理我有一个关于这个代码创建龟的数量问题:使用模型库中的NetLogo

to read-turtles-from-csv 
    file-close-all ; close all open files 
    if not file-exists? "turtles.csv" [ 
    user-message "No file 'turtles.csv' exists! Try pressing WRITE-TURTLES-TO-CSV." 
    stop 
    ] 
    file-open "turtles.csv" ; open the file with the turtle data 

    ; We'll read all the data in a single loop 
    while [ not file-at-end? ] [ 

    let data csv:from-row file-read-line 

    create-turtles 1 [ 
    print "item column 4" 
    show item 4 data 







    ] 
    ] 

    file-close ; make sure to close the file 
end 

我turtles.csv文件只有两行,所以我是什么预计这里是create-turtles 1重复的行数,我有两个代理,其中打印第4列中的2个数字。令人惊讶的是,4只海龟被创建!为什么?

感谢

回答

1

我想知道如果你turtles.csv被读取为具有比它应该更多的线路?尝试执行如下操作:

to read-file 
    file-close-all 
    file-open "turtles.csv" 
    while [not file-at-end?] [ 
    print csv:from-row file-read-line 
    ] 
    file-close-all 
end 

了解Netlogo如何读取文件。看起来你是在正确的轨道上,否则 - 我只是按照你的例子测试了一个类似的文件,并且按照预期得到了我的两只乌龟。使用.csv文件名为“turtle_details.csv”,看起来像:

color size heading 
1 red 2  90 
2 blue 4  180 

我用这个代码产生两个与龟中的变量.csv

extensions [ csv ] 

to setup 
    ca 
    reset-ticks 
    file-close-all 
    file-open "turtle_details.csv" 

    ;; To skip the header row in the while loop, 
    ; read the header row here to move the cursor 
    ; down to the next line. 
    let headings csv:from-row file-read-line 

    while [ not file-at-end? ] [ 
    let data csv:from-row file-read-line 
    print data 
    create-turtles 1 [ 
     set color read-from-string item 0 data 
     set size item 1 data 
     set heading item 2 data 
    ] 
    ] 
    file-close-all 
end 
+1

非常感谢卢克。我犯了一个错误,导致了更多的海龟。数据集有2行,但光标位于第5行的开头,所以它为我创建了5个海龟!它以这种方式工作并创建适当数量的海龟。就在你的代码中,在关于设置颜色,大小和标题的章节中,项目的数量应该分别变为1,2和3,因此它将非常准确。非常感谢你让我知道如何跳过标题。这非常有帮助。 – user710

+0

不用担心!在我的例子中,'.csv'实际上并没有包含行号1和2,这是从我粘贴的其他软件的保留。这就是为什么我使用0,1和2作为'item'索引。作为一个方面说明,我认为如果你将标题赋给一个变量,你可能能够理清你的[早期问题](https://stackoverflow.com/questions/44769763/assign-values-to-turtles-by -searching-through-csv-header-row-in-netlogo)通过比较一个龟值和头值并使用它为你的变量赋值创建一个索引。 –

+0

非常感谢这个好主意。我会尝试。 – user710