在JSON文件(node.js)中需要帮助查找列中的最大值
我在地球物理学课程的计算中有一个任务。 任务基本上是在txt文件的一列中find最大的值(该值是地震的大小,文件包含1990年至2000年的所有地震) 。 然后把这些地震的经度和纬度绘制成地图。 在python中执行任务非常简单,但是由于我正在花一些空闲时间来研究webdev,所以我正在考虑制作一个简单的web应用程序来执行完整的任务。
换句话说,我会上传一个文件,它会自动将最大的地震指定为谷歌地图。
但是因为我在node.js中是一个noob,所以我很难开始这个项目,所以我把它分解成几部分,我需要第一部分的帮助。
我正在考虑将txt.file
转换为.csv
文件,然后将其转换成.json
文件。 我完全不知道应该使用什么algorithm来扫描.json
文件并find给定列的最大值。
这是原始.txt
文件的第一行:
1 5 0 7.0 274 102.000 -3.000
这里是一个.csv
文件,使用在线转换器:
1 5 0 7.0 274 102.000 -3.000
在这里它是.json
文件,再次使用在线转换器:
1\t 5\t 0\t7.0\t274\t102.000\t -3.000
基本上我需要扫描所有的行,并find第五列的最大值。
任何帮助,我将如何开始写这个代码?
非常感谢。
TLDR版本:
需要在具有多行的JSON文件中查找第5列的最大值。
我曾经以此作为一种代码高尔夫风格。 我会忽略通常的“不要堆栈溢出来为你做功课”。 你只是在欺骗自己,孩子这些天,yada yada。
拆分,映射,减less。
let data = require('fs').readFileSync('renan/homework/geophysicist_data.txt') let biggest = data.split('\n') .map(line => line.split(/[ ]+/)[4]) .reduce((a, b) => Math.max(a, b))
加载data
我们分三步处理。
- .split('\ n')通过分割换行符,我们将文本文件分解成一个数组,以便将文本文件中的每一行转换为数组中的一个项目。
- .map(line => line.split(/ [] + /)[4]) 'map'接受这行数组,并在每一行上分别运行一个命令。 对于每一行,我们告诉它,一个或多个空格(
split(/[ ]+/)
)是列分隔符,一旦它被分解到列中取第五列(我们使用[4]
[5]
因为JavaScript从0开始计数)。 - .reduce((a,b)=> Math.max(a,b))现在我们有一个只包含第五列数组的数组,我们可以直接将数组发送到
Math.max
,为我们回答。 万岁!
如果这个数据甚至有点不统一,这将是很容易打破这一点,但我假设,因为这是一个家庭作业,事实并非如此。
祝你好运!
如果你的文件只包含具有相同结构的数字的行,我不会将其转换为csv或json。
我只是去手动parsing.txt
。 这里是代码片段,你可以做到这一点。 我使用了两个外部模块:lodash(用于数据操作的超stream行unility库)和validation器(帮助validationstring):
'use strict'; const fs = require('fs'); const _ = require('lodash'); const os = require('os'); const validator = require('validator'); const parseLine = function (line) { if (!line) { throw new Error('Line not passed'); } //Splitting a line into tokens //Some of tokens are separated with double spaces //So using a regex here let tokens = line.split(/\s+/); //Data validation if (!( //I allowed more tokens per line that 7, but not less tokens && tokens.length >= 7 //Also checking that strings contain numbers //So they will be parsed properly && validator.isDecimal(tokens[4]) && validator.isDecimal(tokens[5]) && validator.isDecimal(tokens[6]) )) { throw new Error('Cannot parse a line'); } //Parsing the values as they come as string return { magnitude: parseFloat(tokens[4]), latitude: parseFloat(tokens[5]), longitude: parseFloat(tokens[6]) } }; //I passed the encoding to readFile because if I would not //data would be a buffer, so we'd have to call .toString('utf8') on it. fs.readFile('./data.txt', 'utf8', (err, data) => { if (err) { console.error(err.stack); throw err; } //Splitting into lines with os.EOL //so our code work on Linux/Windows/Mac let lines = data.split(os.EOL); if (!(lines && lines.length)) { console.log('No lines found.'); return; } //Simple lodash chain to parse all lines //and then find the one with max magnitude let earthquake = _(lines) .map(parseLine) .maxBy('magnitude'); //Simply logging it here //You'll probably put it into a callback/promise //Or send as a response from here console.log(earthquake); });