读取文件中的字符串并将其转换为Julia数组。

huangapple go评论79阅读模式
英文:

Read a string from file and convert into array Julia

问题

我已经成功地将前两个数字放入不同的整数变量中,代码如下:

arq = open("C:\\Users\\Breno Maia\\Desktop\\test.txt", "r")
n = readline(arq)
c = readline(arq)
n = parse(Int64, n)
c = parse(Int64, c)

现在,我需要将第三行和第四行分别放入两个不同的整数数组中。以下是我的解决方案,它可以帮助您完成这个任务:

line3 = readline(arq)
line4 = readline(arq)

# 将第三行分割成整数数组
p3 = parse.(Int64, split(line3))
# 将第四行分割成整数数组
p4 = parse.(Int64, split(line4))

通过上述代码,您可以将第三行和第四行分别存储在整数数组p3p4中。

英文:

I have a text file like this:

  5
  10
  5 3 2 7 4
  2 8 4 2 5

I need to put the first two numbers in to different varibles as integers, I SUCCESSFULLY did that with:

arq = open("C:\\Users\\Breno Maia\\Desktop\\test.txt", "r")
n = readline(arq)
c = readline(arq)
n=parse(Int64, n)
c=parse(Int64, c)

Now, I need to put the third and forth lines in two different arrays of integers. My solution that DOESN'T work is:

line3=readline(arq)
line4 = readline(arq)

p= split(line3, "") //convert string into array
deleteat!(p, findall(x->x==" ", p)) //remove spaces

for i in p
   i=parse(Int64, i)
end

When I print line3, it shows: "SubString{String}["5", "3", "2", "7", "4"]"
plz help. Thank you

答案1

得分: 2

你正在将i重新绑定到正确的值,但实际上没有更新p内的任何引用。

你可以像这样做:p = map(i -> parse(Int, i), p)

英文:

You are rebinding i to the correct value but you are not actually updating any references within p.

You can do something like this: p = map(i -> parse(Int, i), p)

答案2

得分: 0

我建议使用readdlm来简化诸如此类的任务。
前两个值可以在一行中获取,例如:

v1, v2 = filter(x->typeof(x)<:Int, permutedims(readdlm("test.txt"))[:])

以下是获取第一个值、第二个值、第三行和第四行的完整代码:

shell> more test.txt
5
10
5 3 2 7 4
2 8 4 2 5

julia> using DelimitedFiles

julia> dat = readdlm("file.txt")
4×5 Array{Any,2}:
  5   ""  ""  ""  ""
 10   ""  ""  ""  ""
  5   3   2   7   4
  2   8   4   2   5

julia> dat[1,1], dat[2,1], Int.(dat[3,:]), Int.(dat[4,:])
(5, 10, [5, 3, 2, 7, 4], [2, 8, 4, 2, 5])
英文:

I recommend using readdlm to simplify tasks such as this.
The first two values can be get in one line, e.g.:

v1,v2=filter(x-&gt;typeof(x)&lt;:Int, permutedims(readdlm(&quot;test.txt&quot;))[:])

Here is the full code that gets first value, second value, third and fourth line:

shell&gt; more test.txt
5
10
5 3 2 7 4
2 8 4 2 5

julia&gt; using DelimitedFiles

julia&gt; dat = readdlm(&quot;file.txt&quot;)
4&#215;5 Array{Any,2}:
  5   &quot;&quot;   &quot;&quot;   &quot;&quot;   &quot;&quot;
 10   &quot;&quot;   &quot;&quot;   &quot;&quot;   &quot;&quot;
  5  3    2    7    4
  2  8    4    2    5

julia&gt; dat[1,1], dat[2,1], Int.(dat[3,:]), Int.(dat[4,:])
(5, 10, [5, 3, 2, 7, 4], [2, 8, 4, 2, 5])

huangapple
  • 本文由 发表于 2020年1月7日 02:26:15
  • 转载请务必保留本文链接:https://go.coder-hub.com/59617099.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定