我正在尝试读取包含字符串的.txt文件:
Delivery LHR 2018
Delivery LHR 2016
Delivery LHR 2014
Delivery LHR 2011
Delivery LHR 2019
Delivery LHR 1998我已经尝试了下面的代码,但没有工作。当运行file-read时,它报告“期望一个字面值”
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发布于 2018-08-17 23:09:30
你可以用NetLogo自带的the csv extension得到你想要的东西。它至少让您指定了一个分隔符,因此为" ",但是您必须手动读取它将看到的所有空白列。
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发布于 2018-08-17 18:27:06
它不工作的原因可以在NetLogo字典手册(https://ccl.northwestern.edu/netlogo/docs/dictionary.html#file-read)的文件读取描述中找到
...Note字符串需要用引号括起来....
在NetLogo中添加引号不是一个解决方案,因为如果文件中的下一个条目不是数字、列表、字符串、布尔值或特殊值nobody,那么文件读取已经抛出了一个错误。在这种情况下,字符串意味着,它需要用引号括起来。
因此,要将文件读入NetLogo,必须在输入文件的字符串两边加上引号。或者,如果输入文件中的字符串始终具有相同的长度,则可以尝试使用原语file-read-characters读取文件。下面是一个适用于您的输入文件的示例:
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
endhttps://stackoverflow.com/questions/51891563
复制相似问题