我在一个txt文件中有一些数据,格式如下:
byr:1985
eyr:2021 iyr:2011 hgt:175cm pid:163069444 hcl:#18171d
eyr:2023
hcl:#cfa07d ecl:blu hgt:169cm pid:494407412 byr:1936
ecl:zzz
eyr:2036 hgt:109 hcl:#623a2f iyr:1997 byr:2029
cid:169 pid:170290956
hcl:#18171d ecl:oth
pid:266824158 hgt:168cm byr:1992 eyr:2021
我已经有了一个逐行解析txt文件的函数:
function parse_file_by_line(folder, file_name) {
// Read the input file line by line, creating an array of inputs.
const input_file = path.join(__dirname, folder, file_name);
return (input_array = fs.readFileSync(input_file).toString().split("\r\n"));
}
但是,我想解析空行。(文本文件中的空格)。有人建议对“\n\n”进行拆分,我已经尝试过了,但它最终将所有数据放入一个大的数组元素中。我想将空行上的数据拆分到一个数组元素中。例如,第一个索引将是“byr:1985 eyr:2021 iyr:2011 hgt:175cm pid:163069444 hcl:#18171d”。
我想提供一种检查文件字符串的方法。您可以使用json.stringify
检查文件中的字符串类型。通过这种方式,你会发现你的台词结尾是什么。
const fs = require('fs')
const data = fs.readFileSync("./file.txt")
console.log(JSON.stringify(data.toString()));
在我的mac中,这是输出。
"byr:1985\neyr:2021 iyr:2011 hgt:175cm pid:163069444 hcl:#18171d\n\neyr:2023\nhcl:#cfa07d ecl:blu hgt:169cm pid:494407412 byr:1936\n\necl:zzz\neyr:2036 hgt:109 hcl:#623a2f iyr:1997 byr:2029\ncid:169 pid:170290956\n\nhcl:#18171d ecl:oth\npid:266824158 hgt:168cm byr:1992 eyr:2021"