gpt4 book ai didi

string - 读取字符串时如何匹配 float

转载 作者:行者123 更新时间:2023-12-04 23:45:56 25 4
gpt4 key购买 nike

如何匹配浮点数,如 1.234或者使用“E 符号”,如 1.23e04处理字符串时?

例如,假设我想从如下数据文件中读取数字:

0.0 1.295e-03
0.1 1.276e-03
0.2 1.261e-03
0.3 1.247e-03
0.4 1.232e-03
0.5 1.218e-03

目前我编写了自己的函数来转换它包含的数字中的每一行,但它不是很优雅并且根本不便携:具有不同“布局”的数据文件会出错。

这是一个简单的例子,它读取已经显示的数据文件并打印以筛选数字:
function read_line(str)
local a, b, c, d, e = str:match(
"^%s*(%d+)%.(%d+)%s+(%d+)%.(%d+)[Ee]%-*(%d+)")
if str:match("%-") then
e = -tonumber(e)
end
local v1 = a + .1*b
local v2 = (c + .001*d) * 10^e
return v1, v2
end

for line in io.lines("data.txt") do
print(read_line(line))
end

结果如下:
0   0.001295
0.1 0.001276
0.2 0.001261
0.3 0.001247
0.4 0.001232
0.5 0.001218

这确实是我想要达到的结果,但是 有没有更优雅和通用的方法来处理这个问题?

注意:数据文件可以有两列以上的数字,并且可以同时具有浮点表示和“E 表示法”。

最佳答案

假设每一行只包含空格分隔的数字,你可以让 tonumber做繁重的工作,而不是手动匹配数字:

function split_number(str)
local t = {}
for n in str:gmatch("%S+") do
table.insert(t, tonumber(n))
end
return table.unpack(t)
end

for line in io.lines("data.txt") do
print(split_number(line))
end

关于string - 读取字符串时如何匹配 float ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29459952/

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