如何将逐行读取文件并迭代每行中的每个字符相结合? [英] How to combine reading a file line by line and iterating over each character in each line?

查看:26
本文介绍了如何将逐行读取文件并迭代每行中的每个字符相结合?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我从这段代码开始,它只是读取文件中的每一行,而且运行良好:

I started from this code, which just reads every line in a file, and which works well:

use std::io::{BufRead, BufReader};
use std::fs::File;

fn main() {
    let file = File::open("chry.fa").expect("cannot open file");
    let file = BufReader::new(file);
    for line in file.lines() {
        print!("{}", line.unwrap());
    }
}

...但后来我也尝试遍历每一行中的每个字符,如下所示:

... but then I tried to also loop over each character in each line, something like this:

use std::io::{BufRead, BufReader};
use std::fs::File;

fn main() {
    let file = File::open("chry.fa").expect("cannot open file");
    let file = BufReader::new(file);
    for line in file.lines() {
        for c in line.chars() {
            print!("{}", c.unwrap());
        }
    }
}

... 但事实证明,这个最里面的 for 循环是不正确的.我收到以下错误消息:

... but it turns out that this innermost for loop is not correct. I get the following error message:

error[E0599]: no method named `chars` found for type `std::result::Result<std::string::String, std::io::Error>` in the current scope
 --> src/main.rs:8:23
  |
8 |         for c in line.chars() {
  |                       ^^^^^

推荐答案

您需要处理每个 IO 操作可能产生的潜在错误,由 io::Result 表示,它可以包含请求的数据或错误.处理错误的方法有多种.

You need to handle the potential error that could arise from each IO operation, represented by an io::Result which can contain either the requested data or an error. There are different ways to handle errors.

一种方法是忽略它们并读取我们可以获得的任何数据.

One way is to just ignore them and read whatever data we can get.

代码展示了如何做到这一点:

The code shows how this can be done:

use std::io::{BufRead, BufReader};
use std::fs::File;

fn main() {
    let file = File::open("chry.fa").expect("cannot open file");
    let file = BufReader::new(file);
    for line in file.lines().filter_map(|result| result.ok()) {
        for c in line.chars() {
            print!("{}", c);
        }
    }
}

关键点:file.lines() 是一个迭代器,它产生 io::Result.在 filter_map 中,我们将 io::Result 转换为 Option 并过滤任何出现的 None.然后我们只剩下简单的线条(即字符串).

The key points: file.lines() is an iterator that yields io::Result. In the filter_map, we convert the io::Result into an Option and filter any occurrences of None. We're then left with just plain lines (i.e. strings).

这篇关于如何将逐行读取文件并迭代每行中的每个字符相结合?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆