创建 if/else 语句,并根据字符串中的关键字进行扫描



我正在尝试让我的代码搜索特定关键字,并根据这些特定关键字创建扫描器用户输入提示来替换此类关键字。 例如,在 txt 文件中:

嗨,我的名字是<名字>

,你叫什么名字?你的名字<名字>吗?

我喜欢吃<食物,>。是吗?

程序应检测"><名称>",并提示用户为不同的关键字输入两次名称。

到目前为止,我有这个:

// Java program to illustrate reading from Text File
// Using scanner class
import java.io.File;
import java.util.Scanner;
public class TxtOutput{
public static void main(String[] args) throws Exception
{
// pass the path to the file as a parameter
File file = new File("C:\Users\aaron\Documents\TestTXT\test.txt");
Scanner sc = new Scanner(file);
//Types of keywords
//<adjective>, <plural-noun>, <place>, <noun>, <funny-noise>, <person's-name>, <job>, <CITY>, , <Color!>
//, <Exciting-adjective>, <Interersting-Adjective>, <aDvErB>, <NUMBER>, <Plural-noun>, <body-part>, <verb>, 
//<Number>, <verB>, <job-title>, 
String data1 = sc.nextLine();
if (data1.contains("<job>"));
Scanner user_input = new Scanner (System.in);
String job1;
System.out.println("Enter a profession");
job1 = user_input.next(); 
String replacedData1 = data1.replace("<job>", job1 ); 
System.out.println(replacedData1);
}

}

该程序只能检测一个关键字,并且它有一个预制的if和else语句。有没有办法使用扫描仪根据一行中的"><名称>"或"><食物>"等关键字进行 if 和 else 语句? 我不想用不必要的预制 if 和 else 语句轰炸这个程序。我想知道是否有更有效的方法可以做到这一点。

您可以使用正则表达式在整个数据文件中搜索<..>关键字模板,将找到的关键字添加到唯一Set,然后循环访问关键字以请求替换。我想你喜欢这个:

我建议使用正则表达式中的交替|显式指定关键字模板,如下所示:

<adjective>|<plural-noun>|<place>|<noun>|<funny-noise>|<person's-name>|<job>|<CITY>|<Color!>|<Exciting-adjective>|<Interersting-Adjective>|<aDvErB>|<NUMBER>|<Plural-noun>|<body-part>|<verb>|<Number>|<verB>|<job-title>

演示

我们可以使用像<[^<>]+>这样的通用正则表达式,但我不知道您的文件中还有什么。试一试。

将所有内容放在一起,完整的示例:

import java.util.*;
import java.lang.*;
import java.io.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
class Ideone {
public static void main(String[] args) throws java.lang.Exception {
Set < String > uniqueKeywords = new HashSet < String > ();
final String regex = "<adjective>|<plural-noun>|<place>|<noun>|<funny-noise>|<person's-name>|<job>|<CITY>|<Color!>|<Exciting-adjective>|<Interersting-Adjective>|<aDvErB>|<NUMBER>|<Plural-noun>|<body-part>|<verb>|<Number>|<verB>|<job-title>";
final String filecontent = "Text template containing all sorts of .. <adjective>, <plural-noun>, <place>, <noun>, <funny-noise>, <person's-name>, <job>, <CITY>, , <Color!> <Exciting-adjective>, <Interersting-Adjective>, <aDvErB>, <NUMBER>, <Plural-noun>, <body-part>, <verb>,  <Number>, <verB>, <job-title>, String data1 = sc.nextLine(); blah blah";
final Pattern pattern = Pattern.compile(regex, Pattern.DOTALL);
final Matcher matcher = pattern.matcher(filecontent);
while (matcher.find()) {
uniqueKeywords.add(matcher.group(0));
}
Scanner user_input = new Scanner(System.in);
for (String keyword: uniqueKeywords) {
System.out.println("Enter a " + keyword);
String replacement = user_input.next();
String replacedData1 = filecontent.replace(keyword, replacement);
System.out.println(replacedData1);
}
}
}

最新更新