解析TSV文件(ASCII)的惯用方法



我需要解析包含制表符分隔数字的文件,我也知道它们总是只有两个。由于我的文件可能有几GB那么重,我想知道我目前的解析方法是否正确。考虑到我有一个固定的尺寸,看起来我可以更快地制作地图,但我找不到如何制作。

use std::io::{self, prelude::*, BufReader};
type Record = (u32, u32);
fn read(content: &[u8]) -> io::Result<Vec<Record>> {
Ok(BufReader::new(content)
.lines()
.map(|line| {
let nums: Vec<u32> = line
.unwrap()
.split("t")
.map(|s| s.parse::<u32>().unwrap())
.collect();
(nums[0], nums[1])
})
.collect::<Vec<Record>>())
}
fn main() -> io::Result<()> {
let content = "1t1n
2t2n";
let records = read(content.as_bytes())?;
assert_eq!(records.len(), 2);
assert_eq!(records[0], (1, 1));
assert_eq!(records[1], (2, 2));
Ok(())
}

游乐场

如果您的条目只是数字,那么我们可以在map中减少一个内部Vec分配,如下所示:


use std::io::{self, prelude::*, BufReader};
type Record = (u32, u32);
fn read(content: &[u8]) -> io::Result<Vec<Record>> {
return Ok(BufReader::new(content).lines().map(|line| {
let line = line.unwrap();
let mut pair = line.split("t").map(|s|s.parse::<u32>().unwrap());
(pair.next().unwrap(), pair.next().unwrap())
}).collect::<Vec<Record>>())
}
fn main() -> io::Result<()> {
let content = "1t1n
2t2n";
let records = read(content.as_bytes())?;
assert_eq!(records.len(), 2);
assert_eq!(records[0], (1, 1));
assert_eq!(records[1], (2, 2));
Ok(())
}

您可能需要添加更好的错误处理:(

相关内容

最新更新