Reading an Excel .txt file with both text and numbers into NetLogo

岁酱吖の 提交于 2019-11-29 14:59:55

I don't know Excel very well, but I would be surprised if there was no way to add quotes where you need them, either in your spreadsheet or at the time of exporting.

That being said, you can also work this out inside NetLogo.

Using read-from-string (word "[" file-read-line "]") can be very useful, but it only works if your data is in the right format. In your case you will need to use a different approach.

The first thing you will need is a reporter that can split a string according to some delimiter. You can find one in the NetLogo String Extension, but here is one written directly in NetLogo:

to-report split [ string delim ]
  report reduce [
    ifelse-value (?2 = delim)
      [ lput "" ?1 ]
      [ lput word last ?1 ?2 but-last ?1 ]
  ] fput [""] n-values (length string) [ substring string ? (? + 1) ]
end

Calling split "a-b-c" "-", for example, would report ["a" "b" "c"]. But in your case, if I am not mistaken, your fields are separated by tabs. The tab character in NetLogo is \t, so it would be something like split "a\tb\tc" "\t" instead.

Here is how you can read the content of your file now:

to read-content

  let line1 "MyAge\t20\tMyYear\t1994" ; in real life, you'll use file-read-line
  let items split line1 "\t"
  show items ; will be: ["MyAge" "20" "MyYear" "1994"]

  ; If you know the types, you can read the items one by one.
  ; Only apply `read-from-string` to numbers:
  let itemsAB1 (list
    item 0 items
    read-from-string item 1 items
    item 2 items
    read-from-string item 3 items
  )
  show itemsAB1 ; ["MyAge" 20 "MyYear" 1994]

  ; You could also "carefully" try to convert everything to numbers:
  let itemsAB2 map try-to-read items
  show itemsAB2 ; ["MyAge" 20 "MyYear" 1994]

end

to-report try-to-read [ string ]
  let result string
  carefully [ set result read-from-string string ] []
  report result
end

I've shown you two different ways to read the content of a line. The first one is the most straightforward, and only tries to convert (using read-from-string) the items that you already know are numbers.

The second method uses carefully to try to convert every single item using read-from-string. For those that succeed, it reports the converted item. For those that fail, it reports the original string. I've put this here for completeness, but the first method is less likely to cause unforeseen trouble.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!