【问题标题】:How to find certain words in a text file, then find numbers in Java?如何在文本文件中查找某些单词,然后在 Java 中查找数字?
【发布时间】:2013-05-20 06:56:38
【问题描述】:

我有以下文本文件 (answers.txt):

问题 A:23|47|32|20

问题 B:40|50|30|45

问题 C:5|8|11|14

问题 D:20|23|25|30

我需要的是能够读取我告诉它的问题(问题 A,问题 B),然后读取它后面的数字,这些数字由行分隔,并像这样打印出来:

问题 A 的答案:a.23 b.47 c.32 d.20

有谁知道如何做到这一点?我已经坚持了一段时间了。

【问题讨论】:

  • 你能贴出你目前尝试过的代码吗?

标签: java file search text


【解决方案1】:

逐行阅读,首先在“ ”处拆分行。您将得到一个包含“问题”、“A:”和“23|47|32|20”三部分的数组。然后在“|”处拆分第三部分因此您将获得第二个数组,其中包含“23”、“47”、“32”、“20”四个部分。

组合所有以获得您想要的输出。

如果您想了解如何从文件中读取行或溢出的字符串,那么网上有数十亿篇关于如何做到这一点的教程,所以我不会详细介绍它是如何完成的。我相信你能找到他们。

【讨论】:

    【解决方案2】:

    查看此代码! 它假设你有这样的文件格式:

    Problem A:
    23|7|32|20
    Problem B:
    40|50|30|45
    Problem C:
    5|8|11|14
    Problem D:
    20|23|25|30
    

    因为你写了“后面的数字,由行分隔”

    import java.io.File;
    import java.io.FileNotFoundException;
    import java.util.ArrayList;
    import java.util.HashMap;
    import java.util.List;
    import java.util.Map;
    import java.util.Map.Entry;
    import java.util.Scanner;
    
    public class Demo {
    
    public static void main(String[] args) throws FileNotFoundException {
        Scanner sc = new Scanner(new File("answers.txt"));
        List<String> dataList = new ArrayList<String>();
        while(sc.hasNextLine()){
            dataList.add(sc.nextLine());
        }
        System.out.println(dataList);       
        Map<String,String> map = new HashMap<String,String>();
        for(int i=0;i<dataList.size();i=i+2){
            map.put(dataList.get(i),dataList.get(i+1));
        }
    
        for(Entry<String,String> en:map.entrySet()){
            System.out.println(en.getKey()+" : "+en.getValue());
        }
        String problemC = map.get("Problem C:");
        String splitted[] = problemC.split("\\|");
        System.out.println("Get me problem C: "+String.format("a:%s, b:%s, c:%s, d:%s",splitted[0],splitted[1],splitted[2],splitted[3]));
    }
    

    }

    【讨论】:

    • 这不会将“问题 C:”拆分为“问题”和“C:”吗?
    • 那里 "map.get("问题 C:");"不是“问题 C:”
    【解决方案3】:

    希望这会有所帮助!

        public static void main(String args[])
    {
        BufferedReader br = new BufferedReader(new FileReader(new File("answers.txt")));
        String lineRead  = null;
        String problem = "Problem A";//Get this from user Input
        List<String> numberData = new ArrayList<String>();
        while((lineRead = br.readLine())!=null)
        {
            if(lineRead.contains(problem))
            {
                StringTokenizer st = new StringTokenizer(lineRead,":");
                String problemPart = st.nextToken();
                String numbersPart = st.nextToken();
                st = new StringTokenizer(lineRead,"|");
                while(st.hasMoreTokens())
                {
                    String number = st.nextToken();
                    System.out.println("Number is: " + number);
                    numberData.add(number);
                }
                break;
            }
        }
        System.out.println("Answers for " + problem + " : " + numberData );
    }
    

    【讨论】:

      【解决方案4】:

      逐行阅读,用:分割行。您将得到一个包含两部分“问题 A:”和“23|47|32|20”的数组。然后在“|”处拆分第二部分因此您将获得第二个数组,其中包含四个部分“23”、“47”、“32”、“20”。

      结合所有这些,您将获得所需的输出。

      干杯!

      【讨论】:

        【解决方案5】:

        使用java.util.Scanner可以过滤文件中的整数。

        Scanner s = new Scanner (new File ("answers.txt")).useDelimiter("\\s+");
        while (s.hasNext()) {
            if (s.hasNextInt()) { // check if next token is integer
                System.out.print(s.nextInt());
            } else {
                s.next(); // else read the next token
            }
        }
        

        【讨论】:

          【解决方案6】:

          你知道如何逐行阅读吗?如果没有,请查看How to read a large text file line by line in java?

          要子您的字符串数据,有很多方法可以做。您可以根据需要进行分装。这是我的代码..

              String data = yourReader.readLine();
              String problem = data.substring("Problem".length(), data.indexOf(":"));
              System.err.println("Problem is " + problem);
              data = data.substring(data.indexOf(":") + 2, data.length());
              String[] temp = data.split("\\|");
              for (String result : temp) {
                  System.out.println(result);
              }
          

          【讨论】:

            【解决方案7】:

            假设您的示例中总是有四个可能的答案:

            // read complete file in fileAsString
            String regex = "^(Problem \\w+): (\\d+)\\|(\\d+)\\|(\\d+)\\|(\\d+)$";
            Pattern pattern = Pattern.compile(regex);
            Matcher matcher = pattern.matcher(fileAsString);
            //and so on, read all the Problems using matcher.find() and matcher.group(int) to get the parts
            // put in a Map  maybe?
            // output the one you want...
            

            【讨论】:

              【解决方案8】:

              我可能会建议为组织目的创建一个简单的数据类型:

              public class ProblemAnswer {
                private final String problem;
                private final String[] answers;
              
                public ProblemAnswer(String problem, String[] answers) {
                  this.problem = problem;
                  this.answers = new String[answers.length];
                  for (int i = 0; i < answers.length; i++) {
                    this.answers[i] = answers[i];
                  }
                }
              
                public String getProblem() {
                  return this.problem;
                }
              
                public String[] getAnswers() {
                  return this.answers;
                }
              
                public String getA() {
                  return this.answers[0];
                }
              
                public String getB() {
                  return this.answers[1];
                }
              
                public String getC() {
                  return this.answers[2];
                }
              
                public String getD() {
                  return this.answers[3];
                }
              }
              

              那么从文本文件中读取的内容如下所示:

              public void read() {
                Scanner s = new Scanner("answers.txt");
                ArrayList<String> lines = new ArrayList<String>();
                while (s.hasNext()) {
                  lines.add(s.nextLine());//first separate by line  
                }
                ProblemAnswer[] answerKey = new ProblemAnswer[lines.size()];
                for (int i = 0; i < lines.size(); i++) {
                  String[] divide = lines.get(i).split(": "); //0 is the problem name, 1 is the list                 
                                                              //of answers
                  String[] answers = divide[1].split("|");  //an array of the answers to a given
                                                            //question
                  answerKey[i] = new ProblemAnswer(divide[0], answers); //add a new ProblemAnswer 
                                                                        //object to the key
                }
              }
              

              现在为您提供了一个带有 ProblemAnswer 对象的答案键,该对象很容易检查 在getProblem() 方法上进行简单的.equals() 比较,无论匹配什么索引,您都可以将所有答案整齐地排列在同一个对象中。

              【讨论】:

                猜你喜欢
                • 1970-01-01
                • 1970-01-01
                • 1970-01-01
                • 1970-01-01
                • 1970-01-01
                • 1970-01-01
                • 1970-01-01
                • 1970-01-01
                • 1970-01-01
                相关资源
                最近更新 更多