iis服务器助手广告广告
返回顶部
首页 > 资讯 > 前端开发 > html >怎么使用parse
  • 896
分享到

怎么使用parse

2024-04-02 19:04:59 896人浏览 安东尼
摘要

这篇文章主要讲解了“怎么使用parse”,文中的讲解内容简单清晰,易于学习与理解,下面请大家跟着小编的思路慢慢深入,一起来研究和学习“怎么使用parse”吧!1. 真实案例拿一个最近使用 parse 的真实

这篇文章主要讲解了“怎么使用parse”,文中的讲解内容简单清晰,易于学习与理解,下面请大家跟着小编的思路慢慢深入,一起来研究和学习“怎么使用parse”吧!

1. 真实案例

拿一个最近使用 parse 的真实案例来举例说明。

下面是 ovs 一个条流表,现在我需要收集提取一个虚拟机(网口)里有多少流量、多少包流经了这条流表。也就是每个 in_port 对应的  n_bytes、n_packets 的值 。

cookie=0x9816da8e872d717d, duration=298506.364s, table=0, n_packets=480, n_bytes=20160, priority=10,ip,in_port="tapbbdf080b-c2" actions=NORMAL

如果是你,你会怎么做呢?

先以逗号分隔开来,再以等号分隔取出值来?

你不防可以尝试一下,写出来的代码应该和我想象的一样,没有一丝美感而言。

我来给你展示一下,我是怎么做的?

可以看到,我使用了一个叫做 parse 的第三方包,是需要自行安装的

python -m pip install parse

从上面这个案例中,你应该能感受到 parse 对于解析规范的字符串,是非常强大的。

2. parse 的结果

parse 的结果只有两种结果:

没有匹配上,parse 的值为None

>>> parse("halo", "hello") is None True >>>

如果匹配上,parse 的值则 为 Result 实例

>>> parse("hello", "hello world") >>> parse("hello", "hello") <Result () {}> >>>

如果你编写的解析规则,没有为字段定义字段名,也就是匿名字段, Result 将是一个 类似 list 的实例,演示如下:

>>> profile = parse("I am {}, {} years old, {}", "I am Jack, 27 years old, male") >>> profile <Result ('Jack', '27', 'male') {}> >>> profile[0] 'Jack' >>> profile[1] '27' >>> profile[2] 'male'

而如果你编写的解析规则,为字段定义了字段名, Result 将是一个 类似 字典 的实例,演示如下:

>>> profile = parse("I am {name}, {age} years old, {gender}", "I am Jack, 27 years old, male") >>> profile <Result () {'gender': 'male', 'age': '27', 'name': 'Jack'}> >>> profile['name'] 'Jack' >>> profile['age'] '27' >>> profile['gender'] 'male'

3. 重复利用 pattern

和使用 re 一样,parse 同样支持 pattern 复用。

>>> from parse import compile >>>  >>> pattern = compile("I am {}, {} years old, {}") >>> pattern.parse("I am Jack, 27 years old, male") <Result ('Jack', '27', 'male') {}> >>>  >>> pattern.parse("I am Tom, 26 years old, male") <Result ('Tom', '26', 'male') {}>

4. 类型转化

从上面的例子中,你应该能注意到,parse 在获取年龄的时候,变成了一个"27"  ,这是一个字符串,有没有一种办法,可以在提取的时候就按照我们的类型进行转换呢?

你可以这样写。

>>> from parse import parse >>> profile = parse("I am {name}, {age:d} years old, {gender}", "I am Jack, 27 years old, male") >>> profile <Result () {'gender': 'male', 'age': 27, 'name': 'Jack'}> >>> type(profile["age"]) <type 'int'>

除了将其转为 整型,还有其他格式吗?

内置的格式还有很多,比如

匹配时间

>>> parse('Meet at {:tg}', 'Meet at 1/2/2011 11:00 PM') <Result (datetime.datetime(2011, 2, 1, 23, 0),) {}>

更多类型请参考官方文档:

TypeCharacters MatchedOutput
lLetters (ASCII)str
wLetters, numbers and underscorestr
WNot letters, numbers and underscorestr
sWhitespacestr
SNon-whitespacestr
dDigits (effectively integer numbers)int
DNon-digitstr
nNumbers with thousands separators (, or .)int
%Percentage (converted to value/100.0)float
fFixed-point numbersfloat
FDecimal numbersDecimal
eFloating-point numbers with exponent e.g. 1.1e-10, NAN (all case insensitive)float
gGeneral number format (either d, f or e)float
bBinary numbersint
oOctal numbersint
xHexadecimal numbers (lower and upper case)int
tiISO 8601 format date/time e.g. 1972-01-20T10:21:36Z (“T” and “Z” optional)datetime
teRFC2822 e-mail format date/time e.g. Mon, 20 Jan 1972 10:21:36 +1000datetime
tgGlobal (day/month) format date/time e.g. 20/1/1972 10:21:36 AM +1:00datetime
taUS (month/day) format date/time e.g. 1/20/1972 10:21:36 PM +10:30datetime
tcctime() format date/time e.g. Sun Sep 16 01:03:52 1973datetime
thHttp log format date/time e.g. 21/Nov/2011:00:07:11 +0000datetime
tslinux system log format date/time e.g. Nov 9 03:37:44datetime
ttTime e.g. 10:21:36 PM -5:30time

5. 提取时去除空格

去除两边空格

>>> parse('hello {} , hello Python', 'hello     world    , hello python') <Result ('    world   ',) {}> >>>  >>>  >>> parse('hello {:^} , hello python', 'hello     world    , hello python') <Result ('world',) {}>

去除左边空格

>>> parse('hello {:>} , hello python', 'hello     world    , hello python') <Result ('world   ',) {}>

去除右边空格

>>> parse('hello {:<} , hello python', 'hello     world    , hello python') <Result ('    world',) {}>

6. 大小写敏感开关

Parse 默认是大小写不敏感的,你写 hello 和 HELLO 是一样的。

如果你需要区分大小写,那可以加个参数,演示如下:

>>> parse('SPAM', 'spam') <Result () {}> >>> parse('SPAM', 'spam') is None False >>> parse('SPAM', 'spam', case_sensitive=True) is None True

7. 匹配字符数

精确匹配:指定最大字符数

>>> parse('{:.2}{:.2}', 'hello')  # 字符数不符 >>>  >>> parse('{:.2}{:.2}', 'hell')   # 字符数相符 <Result ('he', 'll') {}>

模糊匹配:指定最小字符数

>>> parse('{:.2}{:2}', 'hello')  <Result ('h', 'ello') {}> >>>  >>> parse('{:2}{:2}', 'hello')  <Result ('he', 'llo') {}>

若要在精准/模糊匹配的模式下,再进行格式转换,可以这样写

>>> parse('{:2}{:2}', '1024')  <Result ('10', '24') {}> >>>  >>>  >>> parse('{:2d}{:2d}', '1024')  <Result (10, 24) {}>

8. 三个重要属性

Parse 里有三个非常重要的属性

  • fixed:利用位置提取的匿名字段的元组

  • named:存放有命名的字段的字典

  • spans:存放匹配到字段的位置

下面这段代码,带你了解他们之间有什么不同

>>> profile = parse("I am {name}, {age:d} years old, {}", "I am Jack, 27 years old, male") >>> profile.fixed ('male',) >>> profile.named {'age': 27, 'name': 'Jack'} >>> profile.spans {0: (25, 29), 'age': (11, 13), 'name': (5, 9)} >>>

9. 自定义类型的转换

匹配到的字符串,会做为参数传入对应的函数

比如我们之前讲过的,将字符串转整型

>>> parse("I am {:d}", "I am 27") <Result (27,) {}> >>> type(_[0]) <type 'int'> >>>

其等价于

>>> def myint(string): ...     return int(string) ...  >>>  >>>  >>> parse("I am {:myint}", "I am 27", dict(myint=myint)) <Result (27,) {}> >>> type(_[0]) <type 'int'> >>>

利用它,我们可以定制很多的功能,比如我想把匹配的字符串弄成全大写

>>> def shouty(string): ...    return string.upper() ... >>> parse('{:shouty} world', 'hello world', dict(shouty=shouty)) <Result ('HELLO',) {}> >>>

感谢各位的阅读,以上就是“怎么使用parse”的内容了,经过本文的学习后,相信大家对怎么使用parse这一问题有了更深刻的体会,具体使用情况还需要大家实践验证。这里是编程网,小编将为大家推送更多相关知识点的文章,欢迎关注!

--结束END--

本文标题: 怎么使用parse

本文链接: https://www.lsjlt.com/news/84669.html(转载时请注明来源链接)

有问题或投稿请发送至: 邮箱/279061341@qq.com    QQ/279061341

本篇文章演示代码以及资料文档资料下载

下载Word文档到电脑,方便收藏和打印~

下载Word文档
猜你喜欢
  • 怎么使用parse
    这篇文章主要讲解了“怎么使用parse”,文中的讲解内容简单清晰,易于学习与理解,下面请大家跟着小编的思路慢慢深入,一起来研究和学习“怎么使用parse”吧!1. 真实案例拿一个最近使用 parse 的真实...
    99+
    2024-04-02
  • CSS的parse方法怎么使用
    这篇文章主要讲解了“CSS的parse方法怎么使用”,文中的讲解内容简单清晰,易于学习与理解,下面请大家跟着小编的思路慢慢深入,一起来研究和学习“CSS的parse方法怎么使用”吧! css模块提供了一个...
    99+
    2024-04-02
  • java中parse的使用方法是什么
    在Java中,parse方法通常用于将字符串解析为其他数据类型,比如将字符串解析为整数、浮点数、日期等。具体使用方法取决于要解析的数...
    99+
    2024-03-14
    java
  • c语言中parse函数怎么用
    parse 函数解析字符串,将其转换为由分隔符分隔的令牌列表。步骤:1. 从字符串开头搜索第一个非分隔符字符;2. 继续搜索直到遇到分隔符,并在该分隔符处终止字符串;3. 将令牌存储在令...
    99+
    2024-04-28
    c语言 字符串解析
  • scrapy调用parse()和parse()调用func()的方法
    这篇“scrapy调用parse()和parse()调用func()的方法”文章的知识点大部分人都不太理解,所以小编给大家总结了以下内容,内容详细,步骤清晰,具有一定的借鉴价值,希望大家阅读完这篇文章能有所收获,下面我们一起来看看这篇“sc...
    99+
    2023-06-27
  • c#中parse的用法是什么
    在C#中,Parse方法通常用于将字符串转换为其他数据类型,例如将字符串转换为整数、浮点数、日期等。下面是一些示例用法: 将字符串...
    99+
    2024-03-14
    c#
  • python爬虫urllib库中parse模块urlparse的使用方法
    这篇文章主要介绍了python爬虫urllib库中parse模块urlparse的使用方法,具有一定借鉴价值,感兴趣的朋友可以参考下,希望大家阅读完这篇文章之后大有收获,下面让小编带着大家一起了解一下。在python爬虫urllib库中,u...
    99+
    2023-06-14
  • Ubuntu中的 “Unable to parse package file” 错误怎么解决
    这篇文章主要介绍“Ubuntu中的 “Unable to parse package file” 错误怎么解决”,在日常操作中,相信很多人在Ubuntu中的 “Unable to parse package file” 错误怎么解决问题上存...
    99+
    2023-06-16
  • Python爬虫3-parse编码与利用
    GitHub代码练习地址:①利用parse模拟post请求:https://github.com/Neo-ML/PythonPractice/blob/master/SpiderPrac04_parse-post.py          ...
    99+
    2023-01-30
    爬虫 Python parse
  • mysql从库服务器down机报错Could not parse relay log event entry怎么办
    这篇文章主要为大家展示了“mysql从库服务器down机报错Could not parse relay log event entry怎么办”,内容简而易懂,条理清晰,希望能够帮助大家解决疑惑,下面让小编带...
    99+
    2024-04-02
  • 不需要用到正则的Python文本解析库parse
    目录1. 真实案例2. parse 的结果3. 重复利用 pattern4. 类型转化5. 提取时去除空格6. 大小写敏感开关7. 匹配字符数8. 三个重要属性9. 自定义类型的转换...
    99+
    2024-04-02
  • Canvas怎么使用
    本篇内容介绍了“Canvas怎么使用”的有关知识,在实际案例的操作过程中,不少人都会遇到这样的困境,接下来就让小编带领大家学习一下如何处理这些情况吧!希望大家仔细阅读,能够学有所成!传统的HTML主要用于文本的创建,可以通过<img&...
    99+
    2023-06-04
  • 怎么使用AudioManager
    这篇文章主要讲解了“怎么使用AudioManager”,文中的讲解内容简单清晰,易于学习与理解,下面请大家跟着小编的思路慢慢深入,一起来研究和学习“怎么使用AudioManager”吧!当我们在听歌时,当我们在刷小视频时,当我们在看动漫、在...
    99+
    2023-06-04
  • 怎么使用Explain
    本篇内容主要讲解“怎么使用Explain”,感兴趣的朋友不妨来看看。本文介绍的方法操作简单快捷,实用性强。下面就让小编来带大家学习“怎么使用Explain”吧!执行计划 (Execution Plan)什么执行计划Postgres 有一个强...
    99+
    2023-06-03
  • 怎么使用Smartour
    这篇文章主要讲解了“怎么使用Smartour”,文中的讲解内容简单清晰,易于学习与理解,下面请大家跟着小编的思路慢慢深入,一起来研究和学习“怎么使用Smartour”吧!InstallSmartour&nb...
    99+
    2024-04-02
  • 怎么使用Sass
    这篇“怎么使用Sass”文章的知识点大部分人都不太理解,所以小编给大家总结了以下内容,内容详细,步骤清晰,具有一定的借鉴价值,希望大家阅读完这篇文章能有所收获,下面我们一起来看看这篇“怎么使用Sass”文章...
    99+
    2024-04-02
  • jQuery.holdReady()怎么使用
    这篇文章主要介绍“jQuery.holdReady()怎么使用”的相关知识,小编通过实际案例向大家展示操作过程,操作方法简单快捷,实用性强,希望这篇“jQuery.holdReady()怎么使用”文章能帮助...
    99+
    2024-04-02
  • Protostuff怎么使用
    今天小编给大家分享一下Protostuff怎么使用的相关知识点,内容详细,逻辑清晰,相信大部分人都还太了解这方面的知识,所以分享这篇文章给大家参考一下,希望大家阅读完这篇文章后有所收获,下面我们一起来了解一...
    99+
    2024-04-02
  • htop怎么使用
    本文小编为大家详细介绍“htop怎么使用”,内容详细,步骤清晰,细节处理妥当,希望这篇“htop怎么使用”文章能帮助大家解决疑惑,下面跟着小编的思路慢慢深入,一起来学习新知识吧。 htop使用详解 一....
    99+
    2024-04-02
  • 怎么使用vuex4
    这篇文章主要讲解了“怎么使用vuex4”,文中的讲解内容简单清晰,易于学习与理解,下面请大家跟着小编的思路慢慢深入,一起来研究和学习“怎么使用vuex4”吧!一、安装以及初始化vuex4安装:npm install vu...
    99+
    2023-06-25
软考高级职称资格查询
推荐阅读
编程网,编程工程师的家园,是目前国内优秀的开源技术社区之一,形成了由开源软件库、代码分享、资讯、协作翻译、讨论区和博客等几大频道内容,为IT开发者提供了一个发现、使用、并交流开源技术的平台。
  • 官方手机版

  • 微信公众号

  • 商务合作