【问题标题】:Combining a line counter method with a word counting method将行计数器方法与字计数方法相结合
【发布时间】:2012-11-18 18:56:56
【问题描述】:

我有一个方法可以计算文本文件中单词的出现次数,并返回在特定行上找到该单词的次数。但是,它不会跟踪单词所在的行号。我有一个单独的方法来计算文本文件中的行数,我想将这两种方法组合成一个跟踪行号的方法,并记录每行出现的单词。

我想结合这两种方法来给出类似“单词在 Y 行出现 X 次”的结果

public class Hash
{
   private static final Object dummy = new Object();  // dummy variable
   public void hashbuild()
   {
      File file = new File("getty.txt");
      // LineNumberReader lnr1 = null;
      String line1;
      try{
         Scanner scanner = new Scanner(file);
         //lnr1 = new LineNumberReader(new FileReader("getty.txt"));

         // try{while((line1 = lnr1.readLine()) != null)
         //   {}}catch(Exception e){}

         while(scanner.hasNextLine())
         {
            String line= scanner.nextLine();
            List<String> wordList1 = Arrays.asList(line.split("\\s+"));   
            Map<Object, Integer> hm = new LinkedHashMap<Object, Integer>();
            for (Object item : wordList1)
            {
               Integer count = hm.get(item);
               if (hm.put(item, (count == null ? 1 : count + 1))!=null)
               {
                  System.out.println("Found Duplicate : " +item);
               }
            }
            for ( Object key : hm.keySet() )
            {
               int value = hm.get( key );
               if (value>1)
               {
                  System.out.println(key + " occurs  " + (value) + " times on line # "+lnr1.getLineNumber());
               }
            }
         }
     } catch (FileNotFoundException f)
     {f.printStackTrace();} 
   }
}

这是我原来的计行方法

public void countLines()
{
   LineNumberReader lnr = null; String line;
   try
   {
      lnr = new LineNumberReader(new FileReader("getty.txt"));
      while ((line = lnr.readLine()) != null)
      {
         System.out.print("\n" +lnr.getLineNumber() + " " +line);
      }
      System.out.println("\n");
   }catch(Exception e){}
}

【问题讨论】:

  • 你为什么不使用注释掉的代码?这似乎是为了为您计算行数。它有问题还是您要求不同的方法?
  • 注释掉的代码并没有给我我真正想要的东西。它跟踪行号,但我想将它与另一种方法结合成一个一体化方法。我把它注释掉了,因为它不起作用,但我把它留在里面,这样你就可以看到我想去哪里
  • @Ankur 所以我必须接受我提出的所有问题?不管他们帮助我吗?
  • @user1660948 不是唯一可以帮助您的,就像我在上面在 cmets 中发布的那样

标签: java line-numbers word-count


【解决方案1】:

为什么不只记住 while 循环中的行号?初始化一个新变量,并在调用 nextline 时增加它。

【讨论】:

  • 我不知道在哪里做。因为我有几个循环正在运行
  • 第 16 行:int linenumber = 0; /*然后切换然后在第18行*/ linenumber++;
猜你喜欢
  • 2017-04-28
  • 1970-01-01
  • 2017-10-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-10-27
  • 2023-03-07
相关资源
最近更新 更多