xpresso, 在Java中,代码的Pythonic 方式

分享于 

34分钟阅读

GitHub

  繁體 雙語
The pythonic way to code in Java.
  • 源代码名称:xpresso
  • 源代码网址:http://www.github.com/WantedTechnologies/xpresso
  • xpresso源代码文档
  • xpresso源代码下载
  • Git URL:
    git://www.github.com/WantedTechnologies/xpresso.git
    Git Clone代码到本地:
    git clone http://www.github.com/WantedTechnologies/xpresso
    Subversion代码到本地:
    $ svn co --depth empty http://www.github.com/WantedTechnologies/xpresso
    Checked out revision 1.
    $ cd repo
    $ svn up trunk
    
    xpresso

    Java中代码的Pythonic 方法。

    xpresso是一个 python 库,它。 它允许( 靠近) line-into-line重写 python 代码到Java中。 它也是在Java中直接Prototype化算法的好方法。

    xpresso实现了熟悉的Pythonic 方法(。比如,len,枚举,拆分/联接,切片) 和编码范例(。比如,所有的都是 iterable,列表理解,生成器,lambda表达式,使用谓词过滤 iterables,并用函数修改)。

    xpresso还提供了多个有用的工具,通常是一个衬垫,节省开发人员的时间,使代码更易于阅读: x,x,object,x,x.memo, x,x,x.go, x.timer, x.Json, x.mysql, x.csv,。

    xpresso: 样板更少,更有趣,工作更多。

    许可证:[MIT] ( https://en.wikipedia.org/wikei/MIT_License )。

    用法

    importcom.wantedtech.common.xpresso.x;
    x.print("Hello World!");

    的主要功能

    与类似的类型类型
    importcom.wantedtech.common.xpresso.types.*;

    导入:设置,数据库,列表,元组,DefaultDict,OrderedDict,包,HappyFile,HappySQL

    Slicable和 iterable-str类型
    str city = x.str("New York City");
    x.print(city.slice(4,8));Console:York
    for (String character : city)
     x.print(character);Console:Ne
    wYo
    r
    k
    一个行文件打开

    python:

    withopen("name.txt","r","utf-8") as f:
     #do stuff

    xpresso:

    try (HappyFile f = x.open("name.txt","r","utf-8")) {
     //do stuff}

    在文本和二进制模式下为 write/read/append 工作。

    在 python 中,为读取文本模式而打开的文件是字符串的Iterable:

    python:

    for line in f:
     print line

    xpresso:

    for (String line : f)
     x.print(line);
    元组

    python:

    my_car = ("Honda", "red", 2010, True)

    xpresso:

    tuple myCar = x.tuple("Honda", "red", 2010, true);

    对元组元素的动态 NAME 赋值:

    myCar.name("make","color","year","good");
    x.print(myCar.get("good"),myCar.get("make"),myCar.get("year"));Console:trueHonda2010

    在第1 次调用方法时,返回的值是第1 次,返回值将是元组中剩余未命名元素的最小索引。 subsequent value someName someName someName someName someName的所有后续调用,同样的元素我将会被的get(someName) 返回。

    你还可以定义和使用类型化的元组版本。 例如:

    tuple3<String,String,Integer> myCar = x.tuple3("Honda", "red", 2010);String myCarMake = myCar.left;String myCarColor = myCar.middle;Integer myCarYear = myCar.right;
    tuple2<String,tuple3<String,String,Integer>> item = x.tuple2("car",myCar);String type = item.key; //or, alternatively String type = item.left;tuple3<String,String,Integer> car = item.value; //or, alternatively tuple3<String,String,Integer> car = item.right;
    简洁的标准对象创建

    python:

    trips = ["Dubai","New York","London","Paris","Moscow","London","Saint-Petersburg","New York"]
    russian_cities =set(["Moscow","Saint-Petersburg"])
    rank =dict(("Moscow":30),("Saint-Petersburg":15),("New York":20),("London":10),("Paris":5),("Dubai":32))

    xpresso:

    list<String> trips = x.list("Dubai","New York","London","Paris","Moscow","London","Saint-Petersburg","New York");
    set<String> russianCities = x.set("Moscow","Saint-Petersburg");
    dict<Integer> rank = x.dict(x.tuple("Moscow",30),x.tuple("Saint-Petersburg",15),x.tuple("New York",20),x.tuple("London",10),x.tuple("Paris",5),x.tuple("Dubai",32));
    用户定义函数和谓词
    importcom.wantedtech.common.functional.*Function<Object, String> toUpperCaseFun =newFunction<Object, String>() {
     publicStringapply(Objectvalue) {
     return value.toString().toUpperCase();
     }
    };
    list<String> tripsUp = x.map(toUpperCaseFun, trips);
    x.print(tripsUp);Console: [DUBAI, NEWYORK, LONDON, PARIS, MOSCOW, LONDON, SAINT-PETERSBURG, NEWYORK]
    Predicate<Object> containsO =newPredicate<Object>() {
     publicBooleanapply(Objectvalue) {
     returnx.String("o").in(value.toString()) ?true:false;
     }
    };
    list<String> tripsO = x.filter(containsO, trips);
    x.print(tripsO);Console: [NewYork, London, Moscow, London, NewYork]

    每次想要在一个特定的方法中转换tmodel时,你不需要定义一个新的函数类。 可以使用自动包装任何Java类的任何 static 方法的x.Function 到函数中:

    Function<String,String> myUpper =x.Function(String.class, "toUpperCase");
    iterable = x.map(myUpper, iterable);

    x.Function 方法还可以包装带有多个参数的static 方法:

    Function<tuple3<String,Integer,Boolean>,Double> mySomeFunc =x.Function(Some.class, "someStaticMethod");Function<tuple3<String,Integer,Boolean>,Double> myOtherFunc =x.Function(Other.class, "someOtherMethod");Function<tuple3<String,Integer,Boolean>,Double> funcToUse;if (someCondition) {
     funcToUse = mySomeFunc;
    } else {
     funcToUse = myOtherFunc;
    }double sum;for (element : iterable) {
     sum += funcToUse.apply(x.tuple3(element,intParam,boolParam));
    }

    如果某个类中有多个 static 方法具有相同的NAME,则需要通过提供参数类型指定它的中哪一个要包装:

    Function<tuple3<String,Integer,Boolean>,Double> mySomeFunc =x.Function(Some.class, "someStaticMethod", String.class, Integer.class, Boolean.class);
    表达式

    python:

    best_cities =reversed(sorted(item for item in rank.items(),lambdax: x[0]))

    xpresso:

    list<String> bestCities = x.reverse(x.sort(yield().forEach(rank.items()),x.lambdaF("x: x[0]")));

    更复杂的lambda表达式:

    Predicate<Object> pr = x.lambdaP("x : f0(f1(x[1])) == '''new york'''",x.lower,x.strip);
    Function<Object,Integer> squareFun = x.lambdaF("x : x * x");Function<Object,Integer> fun = x.lambdaF("x : x[0] * 10 * (x[1] - f0(x[2])))",squareFun);

    函数链:

    Function<Object,Integer> incrementFun = x.lambdaF("x : x + 1");Function<Object,Integer> squareFun = x.lambdaF("x : x * x");Function<Object,Integer> chainFun = x.chain(incrementFun,squareFun);

    chainFun 将先递增,然后将它的输入平方。 x.chain(...) 可以两个上的函数作为参数。 链中的最后一个函数必须返回所需输出类型的值。

    下拉列表理解

    python:

    foreign_trips_lower = [city.lower() for city in trips if city notin russian_cities]

    xpresso:

    list<String> foreignTripsLower = x.list(x.<String>yield().apply(x.lower).forEach(trips).unless(x.in(russianCities)));

    python:

    cool_cities =dict([(city.upper(),true) for (city, score) in rank.items() if score >5])

    xpresso:

    dict<Integer> coolCities = x.dict(x.yield("city","_").apply(x.upper).replace(true).where("city","score").in(rank.items()).when(x.lambdaP("city, score : score> 20")));

    python:

    evals = [Trueif value =="good"elseFalsefor value in some_list]

    xpresso:

    list<Boolean> evals = x.list(x.<Boolean>yield().replace(true).when(x.lambdaP("x : x == '''good'''")).replaceOtherwise(false).forEach(someList));

    可以使用列表理解从元素对象中提取属性:

    classPlannedTrip {
     int year;
     String city;
     publicPlannedTrip(intyear, Stringcity) {
     this.year = year;
     this.city = city;
     }
     publicintgetYear() { return year; }
     publicStringgetCity() { return city; }
    }
    list<PlannedTrip> plans = x.list(newPlannedTrip(2015, "Moscow"), newPlannedTrip(2016, "Paris"));
    list<tuple> plansData = x.list(x.yield("year", "city").where("year", "city").in(plans));
    x.print(plansData);Console: [(2015, Moscow), (2016, Paris)]

    你还可以在同一个表达式中过滤提取的值:

    list<tuple> plansData = x.list(x.yield("year", "city").where("year", "city").in(plans).when(x.lambdaP("year, city : year> 2015)));x.print(plansData);Console: [(2016, Paris)]
    RESTful Web服务

    假设我们有一个类SomeMath对象,它有两个方法,我们希望在网络上发布为rest式 Web服务,getSum和 getProduct:

    publicclassSomeMath() {
     publicDoublegetSum(Double[] values) { //we want to publish this onereturn x.sum(values);
     }
     publicDoublegetProduct(Doublex, Doubley) {//and this onereturn x * y;
     }
     publicDoubleanotherMethod(DoublesomethingElse) {//but not this onereturn somethingElse;
     }
    }

    我们需要先注释两个方法,然后启动我们的web服务,以便将我们的SomeMath类转换为一个web服务,以便从网络中调用,然后启动我们的网络服务:

    publicclassSomeMath() {
     publicDoublegetSum(@ExposeAs("values") Double[] values) {
     return x.sum(values);
     }
     publicDoublegetProduct(@ExposeAs("x") Doublex, @ExposeAs("y") Doubley) {
     return x * y;
     }
     publicDoubleanotherMethod(DoublesomethingElse) {
     return somethingElse;
     }
    }WebService ws =x.WebService(newSomeMath(), 8080).start();

    就是这样我们的网络服务已经启动并运行。 测试它。在浏览器中打开以下网址:

    
    http://localhost:8080/SomeMath/getSum?values=5&values=6&values=7
    
    
    
    

    输出:

     
    18.0
    
    
    
     

    现在打开以下网址:

    
    http://localhost:8080/SomeMath/getProduct?x=5&y=10
    
    
    
    

    输出:

     
    50.0
    
    
    
     

    如果方法返回更复杂类的输出类型,比如 java Map和List的标准,或者xpresso列表和,是相应的JSON字符串。

    生成器

    python:

    deffirstn(n):
     num =0while num < n:
     yield num
     num +=1for i in firstn(500000):
     print i

    xpresso:

    publicGenerator<Integer> firstn (finalint n) {
     returnnewGenerator<Integer>() {
     publicvoidgenerate() {
     int num =0;
     while (num < n) {
     yield(num);
     num++;
     }
     }
     };
    }for (int i : firstn(500000)) 
     x.print(i);
    记忆

    作为一个简单的例子,让我们 xerox xerox是一个函数对象的方法应用了字符串"打招呼"count count count count:

    Function<Integer, String> xerox =newFunction<Integer, String>() {
     publicStringapply(Integercount) {
     returnx.String("hello").times(count);
     }
    };

    执行函数的大值是很长的,计算值是。

    为了避免对计数相同值的长时间计算,我们首先使用 x.memo 创建了一个缓存版本的施乐:

    Function<Integer,String> cachedXerox = x.memo(xerox);

    函数的第一个调用。 计算花费了很长时间:

    x.timer.start();String copies = cachedXerox.apply(5000000);
    x.print(x.timer.stop());Console: 18.898s

    第二次调用具有相同的计数,结果是瞬时的:

    x.timer.start();String moreCopies = cachedXerox.apply(5000000);
    x.print(x.timer.stop());Console: 0.0s

    x.memo 可以用于缓存任何Java类型的对象的方法,而不仅仅是函数。 请注意标准 x.timer的用法: 不需要创建其他计时器对象。

    实时并发( 测试版)

    在xpresso中并发是由激发的,因此,它非常简单。 首先,将一个worker定义为谓词的实例:

    Predicate<Channel<Integer>> worker =newPredicate<Channel<Integer>>() {
     publicBooleanapply(Channel<Integer>channel) {
     while (some_condition_true) {
     Integer value = computeValue(); //compute something in parallel channel.send(value); //send the computed value to the channel }
     returntrue; //everything went as expected }
    };

    然后,定义工作人员应该在这些值准备好后立即发送计算值的通道:

    Channel<Integer> channel =x.Channel(Integer.class);//this channel only accepts Integer values

    然后,根据需要启动多个并发工作者:

    x.go(worker, channel);
    x.go(worker, channel);
    x.go(worker, channel);...

    finally,从通道中检索当需要这些值时由工人并发计算的值:

    for (Integer value : channel) {
     x.print(value);
    }
    ( 测试版)

    假设我们有一个要处理的元素列表:

    list<String> elements = x.list("Map","aNd","ReDuce","arE","aWEsome");

    每个元素的过程需要很长的时间,所以我们希望在多核机器上并行化进程。 让处理如下: 当元素以"a"开头时,用大写字母将它放在大写和 Join 中;如果元素不以"a"开头,则使用"~"作为分隔符,然后使用其他 lowercase 语句将它放到 lowercase 和 Join 中。

    让我们定义Mapper和 Reducer:

    importcom.wantedtech.common.xpresso.experimental.concurrency.Mapper;importcom.wantedtech.common.xpresso.experimental.concurrency.Reducer;staticMapper<String,String> mapper =newMapper<String,String>() {
     publicvoidmap(Stringinput) {
     x.Time.sleep(10); //the processing of each element takes a long time :-)if (x.String(input).startsWith("a")) {
     yield("upper", input.toUpperCase()); 
     } else {
     yield("lower", input.toLowerCase());
     }
     }
    };staticReducer<String,String> reducer =newReducer<String,String>() {
     publicvoidreduce(tuple2<String,list<String>> input) {
     yield(input.key,x.String("~").join(input.value));
     }
    };

    映射器按照描述的上面 对字符串实例进行转换,我们的reducer将结果值与"~"连接在一起。

    我们的MapReduce设置已经就绪,让我们开始处理:

    x.timer.start();
    x.print(x.<String,String,String>MapReduce(elements).map(mapper).reduce(reducer), x.timer.stop());Console:{upper:AND~AWESOME~ARE, lower:reduce~map}
    10.013s

    可以看到,所有 5个元素的处理仅花了 10秒,而我们已经定义了每个单个元素的处理需要秒。

    JSON

    记住的秩:

    dict<Integer> rank = x.dict(x.tuple("Moscow",30),x.tuple("Saint-Petersburg",15),x.tuple("New York",20),x.tuple("London",10),x.tuple("Paris",5),x.tuple("Dubai",32));

    让我们先将它的作为字符串进行转储:

    String rankAsString =x.Json(rank).toString();
    x.print(rankAsString);Console: {"New York":20,"London":10,"Saint-Petersburg":15,"Moscow":30,"Dubai":32,"Paris":5}

    现在让我们从它的JSON字符串表示形式创建一个秩的副本:

    dict<Integer> rankCopy =x.String(rankAsString).parseJson();

    比较原始的秩到副本:

    x.print(x.Object(rank).equals(rankCopy));Console:true
    CSV

    从 file: 读取

    try (HappyFile f = x.open("filename.txt","r","utf-8")) {
     for (list<String> row : x.csv(f)) {
     //do stuff }
    }

    或者,只是:

    list<list<String>> data = x.list(x.csv("filename.txt","r","utf-8"));

    写入 file:

    try (HappyFile f = x.open("filename.txt","w","utf-8")) {
     for (list<?> row : data){
     x.csv(f).writerow(row);
     }
    }

    或者,只是:

    try (HappyFile f = x.open("filename.txt","w","utf-8")) {
     f.write(x.csv(data).toString());
    }

    写入 StringBuilder:

    StringBuilder builder =newStringBuilder();for (list<?> row : data) {
     x.csv(builder).writerow(row);
    }String cs = c.toString();

    或者,只是:

    String cs = x.csv(data).toString();
    MySQL
    String host ="host:port";String user ="user";String password ="password";String db ="db";try (HappySQL sql = x.mysql(host, user, password, db)) {
     try (HappySQL sql2 = x.mysql(sql)){
     String query ="SELECT ID FROM "+"tbl_Employees e "+"WHERE e.Name LIKE?";
     for (tuple row : sql.execute(query, "John %")) {
     query ="UPDATE tbl_Employees "+"SET Promoted = 1 "+"WHERE ID =?";
     sql2.execute(query, row.get("ID"));
     }
     }
    }
    扩展字符串函数

    python:

    if"e"in"Hello World":
     #do stuff

    xpresso:

    if(x.String("e").in("Hello World")) {
     //do stuff}

    python:

    colorsPattern ="|".join(["black","green","red","white"]);print colorsPattern>>> black|green|red|white

    xpresso:

    String colorsPattern =x.String("|").join(x.list("black","green","red","white"));
    x.print(colorsPattern);Console: black|green|red|white

    python:

    tokens ="Moscow;London;Paris".split(";")print tokens>>> ['Moscow', 'London', 'Paris']

    xpresso:

    list<String> tokens =x.String("Moscow;London;Paris").split(";");
    x.print(tokens);Console: [Moscow, London, Paris]

    音译:

    String trans =x.String("Чичётка 北亰").translit();
    x.print(trans);Console: Čičëtka bei jing
    x.print(trans.stripAccents());Console:Cicetka bei jing

    将unicode转换为 ascii:

    String unidec =x.String("Чичётка 北亰").unidecode();
    x.print(unidec);Console:Chichiotka bei jing

    近似字符串比较:

    x.print(x.String("Hello World").similarity("Hello Wold!"))Console:91

    输出是 100%与 FuzzyWuzzy 兼容。

    近似 Pattern 匹配:

    x.print(x.String("You are cooding in Java.").search("coding"));Console:8

    获取类似的字符串:

    list<String> lookAlikes =x.String("apple").lookAlikes(x.list("ape", "apples", "peach", "puppy"),50);
    x.print(lookAlikes);Console: [ape, apples]

    标记标记:

    String text ="English is hard. It can be understood through tough thorough thought, though.";for (Sentence s :x.String.EN.tokenize(text)) {
     for (Token t : s) {
     x.print(t);
     }
    }Console:Englishis
    hard.Itcan...
    Part-of-speech标记

    使用xpresso可以很容易地标记任何英文文本,使用非常快和准确的( ~97% ) 3d english-left3words CoreNLP模型:

    importcom.wantedtech.common.xpresso.sentence.Sentence;importcom.wantedtech.common.xpresso.sentence.PosTagger;importcom.wantedtech.common.xpresso.sentence.pos.en.stanford.MaxentPosTagger;PosTagger posTagger =newMaxentPosTagger();String text ="Some English text. Multiple sentences.";for (Sentence sent :x.String.EN.tokenize(text)) {
     posTagger.tag(sent);
     x.print(sent.getAnnotations("pos"));
    }Console: [(Some, DT), (English, NNP), (text, NN), (., .)]
    [(Multiple, JJ), (sentences, NNS), (., .)]
    用于列表。字符串和结构的切片

    python:

    trips = ["Dubai","New York","London","Paris","Moscow","London","Saint-Petersburg","New York"]print trips[2:4]>>> ['London', 'Paris']

    xpresso:

    x.print(trips.slice(2,4));Console: [London, Paris]

    python:

    print trips[:5]>>> ['Dubai','New York','London','Paris','Moscow']

    xpresso:

    x.print(trips.sliceTo(5));Console: [Dubai, NewYork, London, Paris, Moscow]

    支持负和非单位步骤:

    python:

    print trips[::-1]>>> ['New York', 'Saint-Petersburg', 'London', 'Moscow', 'Paris', 'London', 'New York', 'Dubai']

    xpresso:

    x.print(trips.slice(-1));Console: [NewYork, Saint-Petersburg, London, Moscow, Paris, London, NewYork, Dubai]

    python:

    print trips[::2]>>> ['Dubai','London','Moscow','Saint-Petersburg']

    xpresso:

    x.print(trips.slice(2));Console: [Dubai, London, Moscow, Saint-Petersburg]
    切片器对象
    SlicerLAST_THREE= x.sliceFrom(-3);
    x.print(x.String("tic tac toe").slice(LAST_THREE));Console: toe
    Iterable 正规表达式 搜索结果

    python:

    for long_word_match in re.finditer("bw{10,}b",text):
     print long_word_match.group(0)

    xpresso:

    for (Match longWordMatch :x.Regex("bw{10,}b").findIter(text))
     x.print(longWordMatch.group(0));

    python:

    for long_word in re.findall("bw{10,}b",text):
     print long_word

    xpresso:

    for (String longWord :x.Regex("bw{10,}b").findAll(text))
     x.print(longWord);
    替换为函数

    python:

    deftoUpperCaseFun(value):
     return value.group(0).upper()
    text = re.sub("bw{10,}b",toUpperCaseFun,text)

    xpresso:

    Function<Match,String> toUpperCaseFun =newFunction<Match,String>(){
     publicStringapply(Matchvalue) {
     return value.group(0).toUpperCase();
     }
    }
    text =x.Regex("bw{10,}b").sub(toUpperCaseFun,text);
    用字典替换
    dict<String> replacer = x.dict(x.tuple("bad","good"),x.tuple("small","big"),x.tuple("hard","easy"));
    text =x.Regex(replacer).sub(text);
    预定义的正规表达式 模式
    list<String> emails = x.list(x.Regex.EMAIL.findAll("Contact me at john.smith@company.com or john@smith.com."));
    x.print(emails);Console: [smith@company.com, john@smith.com]

    其他模式包括 x.Regex. 链接,x.Regex. 电子邮件,x.Regex. IPV4,x.Regex IPV6,x.Regex. HEX_COLOR,x.Regex. 缩略词,x.Regex. CREDIT_CARD,x.Regex. FLOAT,以及一些国家特定的: 我们的日期,电话,时间,电话,电话,x.Regex. 我们。street_address等。

    标记类型
    Token tok =x.Token("MySQL5");
    x.print(tok.shape(), tok.isCamel(), tok.hasDigits(), tok.hasRussian());Console:ULUUUD, true, true, false
    
    tok = x.Token("Thinking");
    
    
    x.print(tok.stem());
    
    
    
    Console: Think
    
    
    
    
    hashCode ( ),equals(...), 和 compareTo(...) builder

    定义类时:

    @Overrideint hashCode() {
     returnx.Object(this).hashCode();
    }

    ,代码中,xpresso首先查找的成员,然后根据它的成员的值动态计算的哈希代码。

    @Overrideboolean equals(Object obj) {
     returnx.Object(this).equals(obj);
    }

    在 上面 代码中,xpresso首先查找两个对象( this )的成员,然后比较这些成员的值。

    @Overridepublicint compareTo(Object obj) {
     returnx.Object(this).compareTo(obj, fieldName0, fieldName1, ...);
    }

    在 上面 代码中,xpresso首先查找两个对象的成员( ( this ) )。 然后,如果输入字段名称中列出的成员名称与输入字段名称的顺序相同,则将两个对象之间的成员值与输入字段名称的顺序相同。

    断言
    x.assertTrue(condition); // throws IllegalArgumentExceptionx.assertNotNull(parameter); // throws NullPointerExceptionx.assertNotEmpty(iterable); /* throws NullPointerException if iterable is null, throws IllegalArgumentException if iterable is empty */x.assertNotEmpty(string);
    x.assertNotEmpty(array);
    内置迭代器
    • 循环
    for (String letter : x.cycle(x.str("ABC")))
     x.print(letter);Console:ABCABCABC...
    for (String letter : x.cycle(x.list("hello","world"),3))
     x.print(letter);Console: hello
    world
    hello
    world
    hello
    world
    • 重复
    for (String word : x.repeat("cool"))
     x.print(word);Console: cool
    cool
    cool
    cool...
    for (String word : x.repeat("cool",3))
     x.print(word);Console: cool
    cool
    cool
    • 计数数
    for (Integer index : x.countTo(3))
     x.print(index);Console:012
    for (Integer index : x.countFrom(10))
     x.print(index);Console:10111213...
    for (Integer index : x.count(3,10))
     x.print(index);Console:3456789
    for (Integer index : x.count(3,10,3))
     x.print(index);Console:369

    x.count(min, max) 和 x.count(min, max, step) 替换范围( 最小 python,最大) 和范围( 最小,最大,步长)。

    打印任何内容
    x.print("Hello World", 1, true, x.list(1, 2, 3), null);Console:HelloWorld1true [1, 2, 3] NullType
    str phrase ="If you want something done right, you have to do it yourself.";
    list<str> tokens = phrase.split();
    list<list<str>> ngrams = tokens.ngrams(3);
    x.print(ngrams);Console: [[If, you, want], [you, want, something], [something, done, right]..., [do, it, yourself.]]
    largestN和 smallestN
    list<String> cities = x.list("Moscow","San Francisco","Saint-Petersbourg","Rome");
    x.print(x.smallestN(cities,2));Console: [Rome, Moscow]
    list<String> cities = x.list("Moscow","San Francisco","Saint-Petersbourg","Rome");
    x.print(x.largestN(cities,2));Console: [Saint-Petersbourg, SanFrancisco]
    更多
    • 反转 dict.invert();:
    • 展平列表:list.flatten();
    • 使用切片修改列表: trips.setAt(3, 5).values(x.list(1, 2, 3, 4, 5));
    • 大小写不敏感的正规表达式 快捷方式:x.RegexNoCase("bmamab")
    • 用空字符串替换每个 MATCH: x.Regex("[,.;]").clear(inputString)
    • 有关main的更多信息,请参见主类
    的未来
    • HTTP客户端
    • 查找最长的MATCH ( 以 [SequenceMatcher]的精神为例( https://docs.python.org/3.4/library/difflib.html#difflib.SequenceMatcher ) ):
    tuple match =x.String("I like apples.").longestMatch("My girlfriend likes apples too.");
    x.print(match);Console: ("apples", 7, 20)
    • 键入检测: x.String("Random").isMistypingOf("Randon","qwerty") --> true

    JAVA  cod  pythonic  
    相关文章