首页 > 解决方案 > Lua - 分析文本文件中的值

问题描述

我正在将功率(瓦特)值写入文本文件以提取我可以使用的信息。

4.7
4.7
4.8
5.2
5.1
4.6
4.6
4.6

目前我有以下代码可以给我平均值,但我想添加它,以便它告诉我更多信息,例如最高值、最低值、最频繁值是什么,以及如果可能的话记录了任何“0”值(* - 如果可能,最后一个值最好忽略它们..)

local ctr = 0
local sum = 0

for _ in io.lines"/www/EnergyPlug-b.txt" do
    ctr = ctr + 1
end
print(ctr)

for line in io.lines"/www/EnergyPlug-b.txt" do 
    sum = sum + line
end
print(sum)
average = sum / ctr
print(average)

table.insert()我确实探索了通过第一部分创建 Lua 表io.lines,如下所示,但我不确定它有多好?

local rows = {}
-- go over the file line by line
for line in io.lines("/www/EnergyPlug-b.txt") do
  -- if line matches ?.? then insert into table
  local value = line:match("%d%p%d") -- 1.5 
    --print(value) 
    table.insert(rows, value)
end

local arraymax = math.max(unpack(rows))
local arraymin = math.min(unpack(rows))

print (arraymax) -- ?.?
print (arraymin) -- ?.?

如果上述情况合适,我应该如何最好地确定我一开始提到的项目/价值?

标签: lua

解决方案


在第一个片段中,没有理由为 ctr 和 sum 设置单独的循环。您可以在一个循环中完成。

你的第二次剪断没问题。unpack是有限的,因此这不适用于数千个值。

无论如何,您都必须遍历表以获取其他值,这样您也可以在没有该大小限制的情况下确定该循环中的最小值和最大值。

local value = line:match("%d%p%d")如果该文件中只有这些数字,您可以在此处跳过模式匹配。

计算非常简单。我不确定你在这里挣扎什么。

local min = math.huge -- use a value that is definitely bigger than any value
local max = -math.huge -- use a value that is definitely smaller than any value
local counts = {} -- an emtpy table we'll use to count how often each value occurs
local numIngored = 0 -- how many 0 values have we ignored?
for line in io.lines(yourFileName) do
  -- convert string to a number
  local value = tonumber(line)
  -- if we take the value into account
  if value ~= 0.0 then
    -- update min and max values
    min = value < min and value or min
    max = value > max and value or max
    -- update counts
    counts[value] = counts[value] and counts[value] + 1 or 1
  else
    -- count ignored values
    numIgnored = numIgnored + 1
  end
end

我会留给你来获取最常见的值counts


推荐阅读