首页 > 编程语言 >Python 强大的模式匹配工具—Pampy

Python 强大的模式匹配工具—Pampy

时间:2022-12-29 11:33:22浏览次数:63  
标签:Pampy Python dog value Any int other any 模式匹配

 

 

https://pypi.org/project/pampy/

 

 

santinic/pampy: Pampy: The Pattern Matching for Python you always dreamed of. (github.com)

 

All the things you can match

As Pattern you can use any Python type, any class, or any Python value.

The operator _ and built-in types like int or str, extract variables that are passed to functions.

Types and Classes are matched via instanceof(value, pattern).

Iterable Patterns match recursively through all their elements. The same goes for dictionaries.

Pattern ExampleWhat it meansMatched ExampleArguments Passed to functionNOT Matched Example
"hello" only the string "hello" matches "hello" nothing any other value
None only None None nothing any other value
int Any integer 42 42 any other value
float Any float number 2.35 2.35 any other value
str Any string "hello" "hello" any other value
tuple Any tuple (1, 2) (1, 2) any other value
list Any list [1, 2] [1, 2] any other value
MyClass Any instance of MyClass. And any object that extends MyClass. MyClass() that instance any other object
_ Any object (even None)   that value  
ANY The same as _   that value  
(int, int) A tuple made of any two integers (1, 2) 1 and 2 (True, False)
[1, 2, _] A list that starts with 1, 2 and ends with any value [1, 2, 3] 3 [1, 2, 3, 4]
[1, 2, TAIL] A list that start with 1, 2 and ends with any sequence [1, 2, 3, 4] [3, 4] [1, 7, 7, 7]
{'type':'dog', age: _ } Any dict with type: "dog" and with an age {"type":"dog", "age": 3} 3 {"type":"cat", "age":2}
{'type':'dog', age: int } Any dict with type: "dog" and with an int age {"type":"dog", "age": 3} 3 {"type":"dog", "age":2.3}
re.compile('(\w+)-(\w+)-cat$') Any string that matches that regular expression expr "my-fuffy-cat" "my" and "puffy" "fuffy-dog"
Pet(name=_, age=7) Any Pet dataclass with age == 7 Pet('rover', 7) ['rover'] Pet('rover', 8)
Any The same as _   that value  
Union[int, float, None] Any integer or float number or None 2.35 2.35 any other value
Optional[int] The same as Union[int, None] 2 2 any other value
Type[MyClass] Any subclass of MyClass. And any class that extends MyClass. MyClass that class any other object
Callable[[int], float] Any callable with exactly that signature def a(q:int) -> float: ... that function def a(q) -> float: ...
Tuple[MyClass, int, float] The same as (MyClass, int, float)      
Mapping[str, int] Any subtype of Mapping acceptable too any mapping or subtype of mapping with string keys and integer values {'a': 2, 'b': 3} that dict {'a': 'b', 'b': 'c'}
Iterable[int] Any subtype of Iterable acceptable too any iterable or subtype of iterable with integer values range(10) and [1, 2, 3] that iterable ['a', 'b', 'v']

Using default

By default match() is strict. If no pattern matches, it raises a MatchError.

You can instead provide a fallback value using default to be used when nothing matches.

>>> match([1, 2], [1, 2, 3], "whatever")
MatchError: '_' not provided. This case is not handled: [1, 2]

>>> match([1, 2], [1, 2, 3], "whatever", default=False)
False

Using Regular Expressions

Pampy supports Python's Regex. You can pass a compiled regex as pattern, and Pampy is going to run pattern.search(), and then pass to the action function the result of .groups().

def what_is(pet):
    return match(pet,
        re.compile('(\w+)-(\w+)-cat$'),     lambda name, my: 'cat '+name,
        re.compile('(\w+)-(\w+)-dog$'),     lambda name, my: 'dog '+name,
        _,                                  "something else"
    )

what_is('fuffy-my-dog')     # => 'dog fuffy'
what_is('puffy-her-dog')    # => 'dog puffy'
what_is('carla-your-cat')   # => 'cat carla'
what_is('roger-my-hamster') # => 'something else'

标签:Pampy,Python,dog,value,Any,int,other,any,模式匹配
From: https://www.cnblogs.com/sinferwu/p/17012057.html

相关文章

  • 【一】python学习——编码及基础
    1、编码#!/usr/bin/python#-*-coding:UTF-8-*-2、文件#打开一个文件fo=open("foo.txt","w")print"文件名:",fo.name#关闭打开的文件fo.close()......
  • Python_用pypinyin将中文名转化为英文名
    1.在处理数据的时候,很多时候采用的都是英文名的方式,避免遇到一些中文转义错误,这里用pypinyin来进行转化。2.总结大佬经验和自己的积累,目前有两种写法。3.方式:(前提,pypinyi......
  • Python图像处理丨详解图像去雾处理方法
    摘要:本文主要讲解ACE去雾算法、暗通道先验去雾算法以及雾化生成算法。本文分享自华为云社区《[Python图像处理]三十.图像预处理之图像去雾详解(ACE算法和暗通道先验去雾算......
  • 【编程实践】利用 Python 调用图灵机器人 API 实现实时语音聊天及自动回复
    前言什么是图灵机器人在人工智能技术飞速发展的今天,很多以前科幻电影里面的高科技都已经变为现实,而且充斥着我们生活的方方面面,比如说机器人,说说话就能把很多时办了。生......
  • Python进阶—Pandas
    Pandas再来一次文章目录​​一、Series和DataFrame​​​​二、选择数据​​​​三、赋值及操作(增、删、改)​​​​四、处理丢失数据​​​​五、读取并写入文件​​​​......
  • Python进阶—Numpy
    Numpy再来一遍文章目录​​一、Numpy的属性​​​​二、创建array​​​​三、Numpy的运算​​​​四、随机数生成及矩阵的统计​​​​五、Numpy索引​​​​六、合并​......
  • Python学习笔记--高阶技巧(二)
    Socket服务端开发基本步骤如下:socket客户端开发基本步骤如下:1、创建socket对象2、连接到服务器3、发送消息4、接收返回消息5、关闭连接正则表达式基础方法......
  • PYTHON用时变马尔可夫区制转换(MARKOV REGIME SWITCHING)自回归模型分析经济时间序列|附
    全文下载链接:http://tecdat.cn/?p=22617最近我们被客户要求撰写关于MRS的研究报告,包括一些图形和统计输出。本文提供了一个在统计模型中使用马可夫转换模型模型的例子,来......
  • python读取文本中的字典
    首先得明确文本的每行是存的json或者用python的write(str(一个字典))写入的,那么不用借助json模块就能读取为字典,使用eval函数就行,json只能处理带双引号的字符串,但很多时候......
  • opencv-python学习之旅
    opencv-python操作*注:在此笔记中只记录下各种函数的使用,规则详细讲解见https://opencv.apachecn.org/#/docs/4.0.0/2.1-tutorial_py_image_display创建,读取,显示,保存图......