gpt4 book ai didi

java - 如果在字符串集中找到字符串标记,则替换该字符串标记

转载 作者:行者123 更新时间:2023-12-01 12:31:26 25 4
gpt4 key购买 nike

下面的代码应该读取文件 MainFile.txt 中的每一行,检查每一行是否包含 Set 中的 token 。如果包含,请将其替换为“xxx”字符串。然后使用 BufferedWriter 写入一个新文件。输出ConvFile.txt与输入完全相同。

主文件.txt:

car, 18, train, 19, bus,
laptop, 20, tablet, 21, computer,
swim, 22, bike, 23, run,



public class ReplaceWords {

Set<String> wordToReplace;

public ReplaceWords(){
this.wordToReplace = new HashSet<>();
this.wordToReplace.add("18");
this.wordToReplace.add("19");
this.wordToReplace.add("20");
this.wordToReplace.add("21");
this.wordToReplace.add("22");
this.wordToReplace.add("23");
}

public void redactFile(){
String inPathname = "E:\\SkyDrive\\Java\\Coding\\FileChgOne\\MainFile.txt";
String outPathname = "E:\\SkyDrive\\Java\\Coding\\FileChgOne\\ConvFile.txt";
File inFile = new File(inPathname);
File outFile = new File(outPathname);

Scanner bufferedScanner = null;
BufferedWriter bufferedFileWriter = null;



try {
Scanner lineScanner;
String currentLine;

bufferedScanner = new Scanner(new BufferedReader(new FileReader(inFile)));
bufferedFileWriter = new BufferedWriter(new FileWriter(outFile));

while(bufferedScanner.hasNextLine()){
currentLine = bufferedScanner.nextLine();
lineScanner = new Scanner(currentLine);
lineScanner.useDelimiter(",");

while(lineScanner.hasNext()){
String currentToken = lineScanner.next();
if (this.wordToReplace.contains(currentToken)){
bufferedFileWriter.write("xxx, ");
}
else {
bufferedFileWriter.write(currentToken + ", ");
}

}
bufferedFileWriter.newLine();
}

}
catch (Exception en){
System.out.println("error: " + en);
}

finally {
try {
bufferedScanner.close();
bufferedFileWriter.close();
}
catch (Exception en) {
System.out.println(en);
}
}
}
}

输出ConvFile.txt:

car,  18,  train,  19,  bus, 
laptop, 20, tablet, 21, computer,
swim, 22, bike, 23, run,

最佳答案

需要对标记进行修剪,即当扫描仪读取标记时应删除逗号后面的空格:

while(lineScanner.hasNext()){
String currentToken = lineScanner.next();
currentToken = currentToken.trim(); // line to add
if (this.wordToReplace.contains(currentToken)){
bufferedFileWriter.write("xxx, ");
}
else {
bufferedFileWriter.write(currentToken + ", ");
}

}

您还可以按照 Marko Topolnik 在评论中的建议,通过更新 Scanner 的分隔符模式来实现此目的。

lineScanner = new Scanner(currentLine);
lineScanner.useDelimiter("\\s*,\\s*");

\\s* 表示零个或多个空白字符。

关于java - 如果在字符串集中找到字符串标记,则替换该字符串标记,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25898841/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com