首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >从txt文件中读取和导入字符串数据

从txt文件中读取和导入字符串数据
EN

Stack Overflow用户
提问于 2018-08-17 16:44:38
回答 2查看 696关注 0票数 2

我正在尝试读取包含字符串的.txt文件:

代码语言:javascript
复制
Delivery    LHR    2018
Delivery    LHR    2016
Delivery    LHR    2014
Delivery    LHR    2011
Delivery    LHR    2019
Delivery    LHR    1998

我已经尝试了下面的代码,但没有工作。当运行file-read时,它报告“期望一个字面值”

代码语言:javascript
复制
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
EN

回答 2

Stack Overflow用户

发布于 2018-08-17 23:09:30

你可以用NetLogo自带的the csv extension得到你想要的东西。它至少让您指定了一个分隔符,因此为" ",但是您必须手动读取它将看到的所有空白列。

代码语言:javascript
复制
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
票数 3
EN

Stack Overflow用户

发布于 2018-08-17 18:27:06

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

...Note字符串需要用引号括起来....

在NetLogo中添加引号不是一个解决方案,因为如果文件中的下一个条目不是数字、列表、字符串、布尔值或特殊值nobody,那么文件读取已经抛出了一个错误。在这种情况下,字符串意味着,它需要用引号括起来。

因此,要将文件读入NetLogo,必须在输入文件的字符串两边加上引号。或者,如果输入文件中的字符串始终具有相同的长度,则可以尝试使用原语file-read-characters读取文件。下面是一个适用于您的输入文件的示例:

代码语言:javascript
复制
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
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/51891563

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档