开发者

Sentence recognition

开发者 https://www.devze.com 2023-02-15 04:38 出处:网络
I would like my Java program to take science text book questions such as, How far can a cyclist travel in 4.0 h if his average speed is 11.5 km/h?

I would like my Java program to take science text book questions such as,

How far can a cyclist travel in 4.0 h if his average speed is 11.5 km/h?

as a string and then I would like the program to recognize every number and unit mentioned in the question, e.g. in t开发者_如何学编程he example above it will be 4.0 h and 11.5 km/h.

Is it possible to use regex for this purpose?

Many thanks


Solution :
Here is a sample code in java that will match your needs :


import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Regexp {
    public static void main(String[] args) {
        String units = "h|km/h";// Add more units separated by pipes here
        String test = "How far can a cyclist travel in 4.0 h if his average speed is 11.5 km/h?";

        Pattern p = Pattern.compile("\\d+(?:\\.\\d+)?\\s*(?:" + Matcher.quoteReplacement(units) + ")",Pattern.CASE_INSENSITIVE);
        Matcher m = p.matcher(test);

        System.out.println("Numbers and units recognized: ");
        while(m.find()) {
            System.out.println(m.group());
        }
    }
}


It will output :

Numbers and units recognized: 
4.0 h
11.5 km/h


Details :
I assume a number has the following form :
   one or more digits(0-9) optionally followed by a dot and one more digits(0-9)

You can add more units as needed in the pipe separated list units variable

0

精彩评论

暂无评论...
验证码 换一张
取 消