如何在Rust中给字符串中的特定单词着色?

huangapple go评论66阅读模式
英文:

How do I color a specific word in a string in Rust?

问题

我有一个Rust项目。
它的目的是接受两个参数,一个搜索词和一个文件名,然后将文件中包含搜索词的内容以红色打印出来。
我该如何实现这个功能?
以下是代码。

use std::env;
use std::fs::File;
use std::io;
use std::io::prelude::*;
use std::process;

fn main() {
    let args: Vec<String> = env::args().collect();
    let input_args: InputArgs = InputArgs::new(&args).unwrap_or_else(|err| {
        println!("Problem parsing arguments: {}", err);
        process::exit(1)
    });
    println!(
        "Searching for {:?} in file {:?}.",
        input_args.search_term, input_args.file_name
    );
    run(&input_args);
}

fn run(input_args: &InputArgs) -> io::Result<()> {
    let file = File::open(&input_args.file_name)?;
    let reader = io::BufReader::new(file);
    for line in reader.lines() {
        let line = line?;
        println!("{}", line);
    }
    Ok(())
}

struct InputArgs {
    search_term: String,
    file_name: String,
}
impl InputArgs {
    fn new(args: &[String]) -> Result<InputArgs, &str> {
        if args.len() < 3 {
            return Err("Please enter at least 2 arguments.");
        }
        let search_term: String = args[1].clone();
        let file_name: String = args[2].clone();
        return Ok(InputArgs {
            search_term,
            file_name,
        });
    }
}

我已经找到可以为整个字符串着色的库,但没有找到可以仅着色特定单词的库。

英文:

I have a Rust project.
It's purpose is to take 2 arguments, a search term and a file name, and print the contents of the file with the search term in the file colored red.
How do I achieve this?
Below is the code.

use std::env;
use std::fs::File;
use std::io;
use std::io::prelude::*;
use std::process;

fn main() {
    let args: Vec&lt;String&gt; = env::args().collect();
    let input_args: InputArgs = InputArgs::new(&amp;args).unwrap_or_else(|err| {
        println!(&quot;Problem parsing arguments: {}&quot;, err);
        process::exit(1)
    });
    println!(
        &quot;Searching for {:?} in file {:?}.&quot;,
        input_args.search_term, input_args.file_name
    );
    run(&amp;input_args);
}

fn run(input_args: &amp;InputArgs) -&gt; io::Result&lt;()&gt; {
    let file = File::open(&amp;input_args.file_name)?;
    let reader = io::BufReader::new(file);
    for line in reader.lines() {
        let line = line?;
        println!(&quot;{}&quot;, line);
    }
    Ok(())
}

struct InputArgs {
    search_term: String,
    file_name: String,
}
impl InputArgs {
    fn new(args: &amp;[String]) -&gt; Result&lt;InputArgs, &amp;str&gt; {
        if args.len() &lt; 3 {
            return Err(&quot;Please enter at least 2 arguments.&quot;);
        }
        let search_term: String = args[1].clone();
        let file_name: String = args[2].clone();
        return Ok(InputArgs {
            search_term,
            file_name,
        });
    }
}

I have found libraries that can color the entire string but not one that can color only specific words.

答案1

得分: 2

大多数能够给字符串上色的crate实际上都能够给单独的单词上色。例如,colored

use colored::Colorize;

fn main() {
    println!(
        "{} {} {}",
        "or use".cyan(),
        "any".italic().yellow(),
        "string type".cyan()
    );
}

如果你想要构建一个字符串,也可以使用 format! 而不是 println! 来构建实际的字符串,而不是直接输出它,像这样:

use colored::Colorize;

fn main() {
    let mut string = format!(
        "{} {} {}",
        "or use".cyan(),
        "any".italic().yellow(),
        "string type".cyan()
    );

    string.push_str(&"! hello".cyan().to_string());

    println!("{string}");
}
英文:

Most of the crates that color a string actually are capable of coloring individual words. Take for example colored:

use colored::Colorize;

fn main() {
    println!(
        &quot;{} {} {}&quot;,
        &quot;or use&quot;.cyan(),
        &quot;any&quot;.italic().yellow(),
        &quot;string type&quot;.cyan()
    );
}

If you were trying to build a string, you could also use format! instead of println! to build the actual string instead of directly outputting it, like so:

use colored::Colorize;

fn main() {
    let mut string = format!(
        &quot;{} {} {}&quot;,
        &quot;or use&quot;.cyan(),
        &quot;any&quot;.italic().yellow(),
        &quot;string type&quot;.cyan()
    );

    string.push_str(&amp;*&quot;! hello&quot;.cyan().to_string());

    println!(&quot;{string}&quot;);
}

答案2

得分: 0

我已经找到了解决我的问题的方法。
以下是代码。

use colored::Colorize;
use std::env;
use std::fs;

fn main() {
    let args: Vec<String> = env::args().collect();

    let search_term: &str = &args[1];
    let file_name: &str = &args[2];

    println!(
        "在文件 {} 中搜索项 {}。\n",
        file_name.purple().italic(),
        search_term.red().bold()
    );

    search_file(search_term, file_name)
}

fn search_file(search_term: &str, file_name: &str) -> () {
    let content: String = fs::read_to_string(&file_name).expect("\n无法读取文件!");
    for word in content.replace("\n", " \n").split(" ") {
        if word.contains(search_term) {
            print!("{} ", word.red().bold())
        } else {
            print!("{} ", word)
        }
    }
    println!("")
}

希望这有所帮助!

英文:

I have found the solution to my problem.
Below is the code.

use colored::Colorize;
use std::env;
use std::fs;

fn main() {
    let args: Vec&lt;String&gt; = env::args().collect();

    let search_term: &amp;str = &amp;args[1];
    let file_name: &amp;str = &amp;args[2];

    println!(
        &quot;Searching for term {} in file {}.\n&quot;,
        search_term.red().bold(),
        file_name.purple().italic()
    );

    search_file(search_term, file_name)
}

fn search_file(search_term: &amp;str, file_name: &amp;str) -&gt; () {
    let content: String = fs::read_to_string(&amp;file_name).expect(&quot;\nCould not read the file!&quot;);
    for word in content.replace(&quot;\n&quot;, &quot; \n&quot;).split(&quot; &quot;) {
        if word.contains(search_term) {
            print!(&quot;{} &quot;, word.red().bold())
        } else {
            print!(&quot;{} &quot;, word)
        }
    }
    println!(&quot;&quot;)
}

huangapple
  • 本文由 发表于 2023年6月26日 01:08:01
  • 转载请务必保留本文链接:https://go.coder-hub.com/76551574.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定