从分隔文件中解析变量

Ray*_*bel 3 rust

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

1|130|80|120|110|E
2|290|420|90|70|B
3|100|220|30|80|C
Run Code Online (Sandbox Code Playgroud)

然后,我使用 RustBufReader::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());
    }
}
Run Code Online (Sandbox Code Playgroud)

问题是,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]
Run Code Online (Sandbox Code Playgroud)

您知道如何在 Rust 中将此分隔文件解析为变量吗?

She*_*ter 5

由于您的数据是基于行的,您可以使用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);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

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);
    }
}
Run Code Online (Sandbox Code Playgroud)

如果您正在读取结构化数据(例如恰巧由管道分隔的 CSV),您可能还需要查看csv包。