【问题标题】:Where and how to implement the delimiter in my code?在我的代码中在哪里以及如何实现分隔符?
【发布时间】:2018-10-25 13:34:38
【问题描述】:

我制作的程序能够读取文件并打印所有不同单词的列表。但是,我想使用分隔符删除单词开头和结尾的所有逗号和其他字符。但是,我只是不知道如何以正确的方式构建它以及将它放在我的代码中的什么位置。有人可以解释一下在哪里以及如何正确实现它吗?

package nl.ru.ai.SjoerdSam.exercise7;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.Scanner;

public class Concordances
{

  final static int MAX_NR_OF_WORDS=20000;
  public static void main(String[] args) throws FileNotFoundException
  {
    try
    {
      String[] words=new String[MAX_NR_OF_WORDS];
      int[] freqs=new int[MAX_NR_OF_WORDS];
      boolean terminate=true;
      Scanner scanner=openTextFile();
      int nr=findAndCountWords(scanner,words,freqs);
      while(terminate)
      {
        Scanner input=new Scanner(System.in);
        System.out.println("Please enter 'read' to start reading a file and display number of words read, "+"'content' to display content (all currently stored words in the order of apperance), "+"'stop' to stop the program or "+"'count'+ the word you want to count to count the number of occurences of a word, "+"the total number of words and the percantage of occurences.");
        String command=input.nextLine();

        switch(command)
        {
          case "read":
            System.out.println("The number of words in this file is"+nr);
            break;
          case "content":
            displayWords(nr,words,freqs);
            break;
          case "stop":
            terminate=false;
            System.out.println("Program terminated");
            break;
          case "count":
            // Bit stuck here on how to do the count and show the frequency of a single word. if i would actually get the frequency the percentage could be found by dividing the frequency with total number of words found above
            Scanner single=new Scanner(System.in);
            System.out.println("Please type in the word you want to know data of");
            String word=single.nextLine();
            findAndCountWord(scanner,words,word);
            System.out.println("The frequency for the word"+" "+single+" "+"is"+findAndCountWord(single,words,word));
            break;

        }
      }
    }
    catch(IllegalArgumentException e)
    {
      System.out.print(e);
    }
  }
  static Scanner openTextFile() throws FileNotFoundException
  {
    assert (true);
    Scanner input=new Scanner(System.in);
    System.out.println("Please enter file name: ");
    String fileName=input.nextLine();
    FileInputStream inputStream=new FileInputStream(fileName);
    return new Scanner(inputStream);
  }
  static int findAndCountWords(Scanner scanner, String[] words, int[] freqs)
  {
    assert words!=null&&freqs!=null;
    int nr=0;
    while(scanner.hasNext())
    {
      String word=scanner.next();
      if(updateWord(word,words,freqs,nr))
        nr++;
    }
    return nr;
  }
  static boolean updateWord(String word, String[] words, int[] freqs, int nr)
  {
    assert nr>=0&&words!=null&&freqs!=null;
    int pos=sequentialSearch(words,0,nr,word);
    if(pos<nr)
    {
      freqs[pos]++;
      return false;
    } else
    {
      words[pos]=word;
      freqs[pos]=1;
      return true;
    }
  }
  static int sequentialSearch(String[] array, int from, int to, String searchValue)
  {
    assert 0<=from&&0<=to : "Invalidbounds";
    assert array!=null : "Array shouldbeinitialized";
    if(from>to)
      return to;
    int position=from;
    while(position<to&&(!array[position].equals(searchValue)))
      position++;
    return position;
  }
  static void displayFrequencies(int nr, String[] words, int[] freqs)
  {
    assert nr>=0&&words!=null&&freqs!=null;

    for(int i=0;i<nr;i++)
    {
      System.out.println(words[i]+" "+freqs[i]);
    }
  }
  static void displayWords(int nr, String[] words, int[] freqs)
  {
    assert nr>=0&&words!=null&&freqs!=null;

    for(int i=0;i<nr;i++)
    {
      System.out.println(words[i]);
    }
  }

  static int findAndCountWord(Scanner scanner, String[] words, String word)
  {
    assert words!=null;
    int wordCount=0;
    while(scanner.hasNext())
    {
      for(int i=0;i<words.length;i++)
      {
        if(word.equals(words[i]))
        {
          wordCount++;
        }
      }
    }
    return wordCount;
  }
}

此时的输出示例:

U.S.
state's
laws.
principal
office
4557
Melan
Dr.
S.
Fairbanks,
AK,
99712.,
scattered
throughout
numerous
locations.
809
North
1500
West,
Salt
Lake
City,
UT
84116,
(801)
596-1887,
email
business@pglaf.org.
Email
contact
information
http://pglaf.org
information:
Gregory
B.
Newby
Chief
Executive
Director
gbnewby@pglaf.org
4.
Donations

【问题讨论】:

  • String.replace() 是否有任何理由不适合您的需求?
  • 是的,这是 uni 的作业。到目前为止还不允许使用该命令。
  • 输出应该是什么?例如,business@pglaf.org.http://pglaf.org 会发生什么?是否有应删除的特定字符列表?
  • 输出应该是最符合逻辑的单词列表。因此,我必须根据三个文件自行选择要删除的内容和不删除的内容。它不必是完美的,但它应该删除最常见的奇怪符号。所以;剥离前导和尾随非字母。
  • 我应该逐步更改分隔符以获得越来越好的输出,而不会出现奇怪的单词。

标签: java arrays list delimiter


【解决方案1】:

这不是最漂亮的,但它应该可以工作。

String str = "!!!!@word's!@#";
String temp = "";
boolean done = false;
for (int i = 0; i < str.length(); i++) {
    char currentChar = str.charAt(i);
    if (Character.isLetter(currentChar) && !done) {
        done = true;
        temp += currentChar;
    } else if (done) {
        temp += currentChar;
    }
}

str = "";
done = false;
for (int i = temp.length() - 1; i >= 0; i--) {
    char currentChar = temp.charAt(i);
    if (Character.isLetter(currentChar) && !done) {
        str += currentChar;
        done = true;
    } else if (done) {
        str += currentChar;
    }
}
StringBuilder sb = new StringBuilder(str);

str = sb.reverse().toString();
System.out.println(str);

输出是单词的

【讨论】:

  • Stringbuilder 会更有效率,但你明白了基本的想法。
  • 去掉所有非字母字符。问题似乎是如何去除所有前导和尾随非字母,但应保留内部非字母字符。
  • 啊啊啊,我来补充一下
  • 非常感谢你们!还有一件事;您知道计算文件所有单词的简单解决方案吗?所以不是不同单词的数量,而是文件中的每个单词。
  • 只使用计数器?整数计数 = 0;并且每次从文件中抓取一个单词时,调用 count++;
猜你喜欢
  • 1970-01-01
  • 2019-07-30
  • 1970-01-01
  • 1970-01-01
  • 2020-03-19
  • 1970-01-01
  • 2014-08-31
  • 1970-01-01
  • 2021-04-22
相关资源
最近更新 更多