【问题标题】:Is it possible to connect two "while" cycles to get the answer? Java是否可以连接两个“while”循环来获得答案?爪哇
【发布时间】:2018-05-23 09:53:18
【问题描述】:

我想首先从文件中读取行,将文本重写到另一个文件

File dir = new File("C:/Users/PC/workspace/uplo/");

我得到的文件:

   String source = dir.getCanonicalPath() + File.separator + "Output.txt";

我要写入的文件:

   String dest = dir.getCanonicalPath() + File.separator + "Final.txt";

   File fin = new File(source);
   FileInputStream fis = new FileInputStream(fin);
   BufferedReader in = new BufferedReader(new InputStreamReader(fis, "UTF-8"));

   OutputStreamWriter fstream = new OutputStreamWriter(new FileOutputStream(dest, true), "UTF-8");

   BufferedWriter out = new BufferedWriter(fstream);

循环将内容重写到新的 Final.txt 文件:

   String aLine = null;
   while ((aLine = in.readLine()) != null) {

我想用这个循环从文件中删除重复项,但不幸的是我不知道该怎么做......

   String regex = "\\b(\\w+)(\\s+\\1\\b)+";
   Pattern p = Pattern.compile(regex, Pattern.CASE_INSENSITIVE);

   Matcher m = p.matcher(aLine);
   while (m.find()) {
        aLine = aLine.replaceAll(m.group(), m.group(1));
    }

   out.write(aLine);
   out.newLine();
   }

       in.close();
       out.close();

有人可以帮我解决这个问题吗?我正在做我的家庭作业,我不能把它合并在一起:)

例如我想重写文本:

   Hello hello hello my name name Name is Arthur and I live in in Lithuania.

收件人:

   Hello my name is Arthur and I live in Lithuania.

【问题讨论】:

  • 您想逐行删除重复项,或者这也适用于行之间的重复项,例如"Hello!\n"Hello!"?
  • 老实说,我不知道是什么问题。您似乎拥有一切,而且对我来说似乎工作正常。您究竟在哪里遇到了麻烦?
  • @EdwinDalorzo 也行间
  • @EdwinDalorzo 我得到的文本与原始文本相同,程序不会删除重复项
  • 我刚试过你的程序,它对我来说很好用。正则表达式可能会有所改进,因为它会因某些带有撇号的单词(例如“不要”)而失败,但除此之外它对我来说很好。

标签: java regex file while-loop cycle


【解决方案1】:

我刚刚运行了您的代码,它对我来说运行良好。我可能会稍微改进一下正则表达式,以包含当前实现中不接受的其他单词,例如带有撇号的单词,例如“不要”、“不会”等。

但这可能没什么大不了的。我成功地尝试了以下方法:

String regex = "\\b((\\w|\\p{Punct})+)(\\s+\\1\\b)+";
Pattern p = Pattern.compile(regex, Pattern.CASE_INSENSITIVE);

try(BufferedWriter out = new BufferedWriter(new OutputStreamWriter(System.out))) {
    try (BufferedReader in = new BufferedReader(new InputStreamReader(System.in))) {
        String aLine;
        while ((aLine = in.readLine()) != null) {
            Matcher m = p.matcher(aLine);
            while (m.find()) {
                aLine = aLine.replaceAll(m.group(), m.group(1));
            }
            out.write(aLine);
            out.newLine();
            out.flush();
        }
    }
}

我提供输入“不要担心,要快乐快乐!”然后我回复“别担心,开心点!”

我不确定这个示例是否对您的问题有帮助,因为我不清楚您到底在哪里遇到了问题,而且您的原始代码似乎没问题。

【讨论】:

  • 我知道正则表达式工作正常,但问题是我得到的文件与原始文本相同,任何正则表达式 :) 所以我不知道,错误在哪里。两个 while 循环都工作正常,但似乎循环中的循环不是
  • 我发现了一个问题,它不适用于立陶宛语:/为什么?
  • 正如我所说,我采用了您的程序并逐字逐句运行,它对我来说效果很好。您确定要检查“final.txt”吗?请注意,您的输入文件实际上称为“Output.txt”,这非常令人困惑。重复数据删除的结果位于“Final.txt”中。我运行了你的程序,“Final.txt”看起来很好。
  • 哦,我明白了!为此,您需要使用 unicode 正则表达式
  • 你能帮忙吗? :)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-09-02
  • 1970-01-01
  • 2018-05-24
  • 2022-10-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多