【问题标题】:Parsing variable from delimited file从分隔文件解析变量
【发布时间】:2015-10-23 04:32:35
【问题描述】:

我有一些由管道| 符号分隔的文件内容。命名为important.txt

1|130|80|120|110|E
2|290|420|90|70|B
3|100|220|30|80|C

然后,我使用 Rust BufReader::split 来读取它的内容。

use std::error::Error;
use std::fs::File;
use std::io::BufReader;
use std::io::Prelude::*;
use std::path::Path;

fn main() {
    let path = Path::new("important.txt");
    let display = path.display();

    //Open read-only
    let file = match File::open(&path) {
        Err(why) => panic!("can't open {}: {}", display,
                           Error::description(why)),
        Ok(file) => file,
    }

    //Read each line
    let reader = BufReader::new(&file);
    for vars in reader.split(b'|') {
        println!("{:?}\n", vars.unwrap());
    }
}

问题是,vars.unwrap() 会返回字节而不是字符串。

[49]
[49, 51, 48]
[56, 48]
[49, 50, 48]
[49, 49, 48]
[69, 10, 50]
[50, 57, 48]
[52, 50, 48]
[57, 48]
[55, 48]
[66, 10, 51]
[49, 48, 48]
[50, 50, 48]
[51, 48]
[56, 48]
[67, 10]

你知道如何在 Rust 中将这个分隔文件解析为变量吗?

【问题讨论】:

    标签: rust


    【解决方案1】:

    由于您的数据是基于行的,您可以使用BufRead::lines

    use std::io::{BufReader, BufRead};
    
    fn main() {
        let input = r#"1|130|80|120|110|E
    2|290|420|90|70|B
    3|100|220|30|80|C
    "#;
    
        let reader = BufReader::new(input.as_bytes());
    
        for line in reader.lines() {
            for value in line.unwrap().split('|') {
                println!("{}", value);
            }
        }
    }
    

    这为输入中的每一行提供了一个在 Strings 上的迭代器。然后你使用str::split 来获取碎片。

    或者,您可以使用已有的&[u8] 并使用str::from_utf8 从中创建一个字符串:

    use std::io::{BufReader, BufRead};
    use std::str;
    
    fn main() {
        let input = r#"1|130|80|120|110|E
    2|290|420|90|70|B
    3|100|220|30|80|C
    "#;
    
        let reader = BufReader::new(input.as_bytes());
    
        for vars in reader.split(b'|') {
            let bytes = vars.unwrap();
            let s = str::from_utf8(&bytes).unwrap();
            println!("{}", s);
        }
    }
    

    如果您正在读取像 CSV 这样恰好是管道分隔的结构化数据,您可能还需要查看 csv crate。

    【讨论】:

    • 知道了。非常感谢。
    猜你喜欢
    • 2017-07-17
    • 2016-05-25
    • 1970-01-01
    • 1970-01-01
    • 2015-01-18
    • 1970-01-01
    • 2013-06-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多