Netlogo-从txt文件读取和导入字符串数据
我正在尝试读取包含字符串的.txt文件:Netlogo-从txt文件读取和导入字符串数据,netlogo,Netlogo,我正在尝试读取包含字符串的.txt文件: Delivery LHR 2018 Delivery LHR 2016 Delivery LHR 2014 Delivery LHR 2011 Delivery LHR 2019 Delivery LHR 1998 我尝试了以下代码,但没有工作。当运行文件读取时,它报告了“预期文本值” globals [input] to setup set input [] file-
Delivery LHR 2018
Delivery LHR 2016
Delivery LHR 2014
Delivery LHR 2011
Delivery LHR 2019
Delivery LHR 1998
我尝试了以下代码,但没有工作。当运行文件读取时,它报告了“预期文本值”
globals [input]
to setup
set input []
file-open "test.txt"
while [not file-at-end?]
[
let a quote file-read
let b quote file-read
set input lput a input
set input lput b input
print input
]
file-close
end
to-report quote [ #thing ]
ifelse is-number? #thing
[ report #thing ]
[ report (word "\"" #thing "\"") ]
end
无法工作的原因可以在NetLogo字典手册()中的文件读取说明中找到 […]请注意字符串周围需要有引号。[…] 如果文件中的下一个条目不是number、list、string、boolean或特殊值nobody,则在NetLogo中添加引号不是解决方案,因为文件读取已引发错误。在本例中,字符串的意思是,需要在其周围加引号 因此,要将文件读入NetLogo,必须在输入文件的字符串周围加引号。或者,如果输入文件中的字符串始终具有相同的长度,则可以尝试使用原语
文件读取字符
读取文件。下面是一个应用于输入文件的示例:
to setup
file-open "test.txt"
while [not file-at-end?]
[
let a file-read-characters 8
let skip file-read-characters 4
let b file-read-characters 3
let c file-read
print (list a b c)
]
file-close
end
你可以通过NetLogo得到你想要的东西。它至少让你指定了一个定界符,所以<代码>“/COD>”,但是你必须手动读取它所看到的所有空白列。
extensions [csv]
globals [input]
to setup
set input []
let lines (csv:from-file "test.txt" " ")
foreach lines [ line ->
let col1 (item 0 line)
let i 1
while [item i line = ""] [ set i (i + 1) ]
let col2 (item i line)
show col2
set i (i + 1)
while [item i line = ""] [ set i (i + 1) ]
let col3 (item i line)
show col3
set input lput col1 input
]
show input
end
谢谢,但这还远远不够理想。输入文件可以同时包含数字和字符串,并且长度和顺序不是固定的,这是一个常见的用例。没有办法巧妙地添加引号真的很痛苦…@Jack-这并不是说它是数字和字符串的组合-正如你所指出的,这是非常常见的。相反,我认为是固定宽度的文件格式导致了这个问题。这也是我的建议。但是请注意,CSV扩展只接受单字符分隔符(它将只使用分隔符的第一个字符)。然而,剥离空白实际上比您在这里列出的要容易。您可以使用
map[row->filter[field->not empty?field]row](csv:来自文件“test.txt”)在一行中完成这项操作
@BryanHead-我需要使用filter[field->is number?field or not empty?field]
,或者年份值抛出错误-这可能与版本有关?我使用的是6.0.2。使用文本编辑器来实际引入NetLogo期望的引号和逗号可能是最容易的,尤其是如果您知道如何为搜索和替换构造正则表达式的话