Netlogo-从txt文件读取和导入字符串数据

时间:2018-08-17 08:44:38

标签: 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-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

2 个答案:

答案 0 :(得分:3)

您可以使用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

答案 1 :(得分:2)

在NetLogo词典手册(https://ccl.northwestern.edu/netlogo/docs/dictionary.html#file-read)的文件读取说明中可以找到它不起作用的原因

[...]请注意,字符串中必须有引号。[...]

在NetLogo中添加引号不是解决方案,因为如果文件中的下一个条目不是数字,列表,字符串,布尔值或特殊值none之一,则文件读取已经引发错误。在这种情况下,字符串意味着必须在其周围加上引号。

因此,要将文件读入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
end