我必须更正文件中的文本。
什么时候是逗号或点,我必须更改到正确的位置,例如
“这是,一些文字,请更正。这段文字。”改为“这是,一些文字,请更正。这段文字。”
我注意到我的代码无法正常工作。对于点他根本不起作用,对于逗号之前添加逗号腾出空间。
你有什么提示吗?
FileReader fr = null;
String line = "";
String result="";
String []array;
String []array2;
String result2="";
// open the file
try {
fr = new FileReader("file.txt");
} catch (FileNotFoundException e) {
System.out.println("Can not open the file!");
System.exit(1);
}
BufferedReader bfr = new BufferedReader(fr);
// read the lines:
try {
while((line = bfr.readLine()) != null){
array=line.split(",");
for(int i=0;i<array.length;i++){
//if i not equal to end(at the end has to be period)
if(i!=array.length-1){
array[i]+=",";
}
result+=array[i];
}
// System.out.println(result);
array2=result.split("\\.");
for(int i=0;i<array2.length;i++){
System.out.println(array2[i]);
array[i]+="\\.";
result2+=array2[i];
}
System.out.println(result2);
}
} catch (IOException e) {
System.out.println("Can not read the file!");
System.exit(2);
}
// close the file
try {
fr.close();
} catch (IOException e) {
System.out.println("error can not close the file");
System.exit(3);
}
最佳答案
首先假设您可以使用正则表达式。这是执行您想要的操作的简单方法:
import java.io.*;
class CorrectFile
{
public static void main(String[] args)
{
FileReader fr = null;
String line = "";
String result="";
// open the file
try {
fr = new FileReader("file.txt");
} catch (FileNotFoundException e) {
System.out.println("Can not open the file!");
System.exit(1);
}
BufferedReader bfr = new BufferedReader(fr);
// read the lines:
try {
while((line = bfr.readLine()) != null){
line = line.trim().replaceAll("\\s*([,,.])\\s*", "$1 ");
System.out.println(line);
}
} catch (IOException e) {
System.out.println("Can not read the file!");
System.exit(2);
}
// close the file
try {
fr.close();
} catch (IOException e) {
System.out.println("error can not close the file");
System.exit(3);
}
}
}
最重要的是这一行:line = line.trim().replaceAll("\\s*([,,.])\\s*", "$1 ");
。首先,您阅读的每一行两端都可能包含空格。如果是的话,String.trim() 将删除它们。接下来,取出字符串(去掉两端的空格),我们想将“多个空格+一个逗号+多个空格”之类的内容替换为“一个逗号+一个空格”,同样的内容用“点”。“\s”是空格的正则表达式,“\s*”是“零个或任意数量的空格”的正则表达式。“[]”表示字符组,“[,,.]”表示“, ”或“.”,中间的逗号只是一个分隔符。这里我们需要对字符串转义“\”,所以现在我们有“\s*([,,.])\s*”,这意味着让我们替换一些任意的后跟一个“,”或“.”的空格数量,后跟任意数量的空格,其中“,”后跟一个空格或“.”后跟一个空格。此处的括号构成元素其中有一个捕获组,其目的是“保存”找到的匹配项(这里是“,”或“.”),我们稍后在示例中将其用作“$1”。因此,我们将能够替换我们找到的匹配项是“,”或“.”,无论匹配是什么。由于逗号或点后面需要一个空格,因此我们在其中添加一个空格,使其成为“$1”。
现在,让我们看看你原来的东西有什么问题,以及为什么我说 String.split() 可能不是一个好主意。
除了创建大量新的 String 对象之外,最明显的问题是您(可能是拼写错误)使用了 array[i]+=".";
而不是 array2[i]+=".";
.但最不那么明显的问题来自 String.split() 方法,该方法实际上在分割数组中的字符串段中包含空格。最后一个数组元素甚至只包含一个空格。
关于java - 从文件中读取文本并进行更正(逗号和点)[Java],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27382193/