英文:
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))
通过上述代码,您可以将第三行和第四行分别存储在整数数组p3
和p4
中。
英文:
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->typeof(x)<:Int, permutedims(readdlm("test.txt"))[:])
Here is the full code that gets first value, second value, third and fourth line:
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])
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论