gpt4 book ai didi

ascii - 在 Julia 中,如何将 ASCII 十进制列表转换为字符串?

转载 作者:行者123 更新时间:2023-12-01 08:26:03 24 4
gpt4 key购买 nike

域名:我要转换 [125, 119, 48, 126, 40]输出字符串,}w0~(
举一个真实的例子,我正在处理 fastq 格式的序列数据( Here is a link to the library imported )。
cat example.fastq输出以下内容:

@some/random/identifier
ACTAG
+
}w0~(

下面的 julia 代码演示了读取 fastq 文件:
import BioSequences.FASTQ


fastq_stream = FASTQ.Reader(open("example.fastq", "r"))
for record in fastq_stream
# Still need to learn, why this offset of 33?
println(
Vector{Int8}(FASTQ.quality(record, :sanger)) .+ 33
)
println(
String(FASTQ.sequence(record))
)
println(
String(FASTQ.identifier(record))
)
break
end
close(fastq_stream)

此代码打印以下内容:
[125, 119, 48, 126, 40]
ACTAG
some/random/identifier

我不想将这些信息存储在列表中。我更愿意将其转换为字符串。所以我在这里寻找的输出是:
}w0~(
ACTAG
some/random/identifier

最佳答案

julia> String(UInt8.([125, 119, 48, 126, 40]))
"}w0~("

解释

在 Julia 中,字符串是使用一组字节构造的。如果您只使用 ASCII,那么字符字节映射很简单,您可以直接处理原始数据(这也是最快的方法)。

请注意,由于 Julia 字符串是不可变的,当从原始字节创建字符串时,初始字节变得不可用 - 这也意味着没有数据被复制到 String 中。创建过程。看看下面的例子:
julia> mybytes = UInt8.([125, 119, 48, 126, 40]);

julia> mystring = String(mybytes)
"}w0~("

julia> mybytes
0-element Array{UInt8,1}

性能说明
String Julia 中的 s 没有内化。在分析场景中始终考虑使用 Symbol s 而不是 String s。在某些情况下使用 temperature=:hot而不是 temperature="hot"可能意味着执行时间缩短 3 倍。

编辑 - 性能测试
julia> using Random, BenchmarkTools;Random.seed!(0);

bb = rand(33:126,1000);

julia> @btime join(Char.($bb));
31.573 μs (13 allocations: 6.56 KiB)

julia> @btime String(UInt8.($bb));
711.111 ns (2 allocations: 2.13 KiB)
String(UInt8.($bb))速度提高了 40 倍以上,并且使用了 1/3 的内存

关于ascii - 在 Julia 中,如何将 ASCII 十进制列表转换为字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54979411/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com