在Netlogo的模型库中使用CSV示例创建代理
我有一个关于根据该代码创建的海龟数量的问题:在Netlogo的模型库中使用CSV示例创建代理,csv,netlogo,agent-based-modeling,Csv,Netlogo,Agent Based Modeling,我有一个关于根据该代码创建的海龟数量的问题: 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" ;
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文件只有两行,所以我希望这里的createturtles 1会针对行数重复,我有两个代理,第4列中的2个数字会被打印出来。令人惊讶的是,4只海龟被创造出来了!为什么?
谢谢我想知道你的
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如何读取文件。看起来你的思路是对的,否则-我只是按照你的例子测试了一个类似的文件,我得到了我的两个海龟。使用名为“turtle\u details.csv”的.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
非常感谢,卢克。我犯了一个错误,导致更多的海龟。数据集有2行,但光标位于第5行的开头,所以它为我创建了5个海龟!它确实以这种方式工作,并创造了适当数量的海龟。就在您的代码中,在关于设置颜色、大小和标题的部分中,项目的数量应该分别更改为1、2和3,因此它将非常精确。非常感谢你让我知道如何跳过标题。非常有用,不用担心!在我的示例中,
.csv
实际上不包括行号1和2,这是我粘贴的其他软件的保留。这就是为什么我使用0、1和2作为项的索引。作为补充说明,我认为如果你将标题分配给一个变量,你可以通过比较海龟值和标题值来整理你的数据,并使用它为你的变量分配创建一个索引。非常感谢你的好主意。我会试试的。非常感谢。将变量分配给标题的想法非常有效,但仍然存在其他问题,我将其作为一个新问题提出。