python case sensitive_用上这个 Python 文本解析库,让你和『正则』说 拜拜了

从一段指定的字符串中,取得期望的数据,正常人都会想到正则表达式吧?

写过正则表达式的人都知道,正则表达式入门不难,写起来也容易。

但是正则表达式几乎没有可读性可言,维护起来,真的会让人抓狂,别以为这段正则是你写的就可以驾驭它,过个一个月你可能就不认识它了。

完全可以说,天下苦正则久矣。

>给大家推荐我自己的qun:850973621

把各种 python 的高效的使用技

巧用电子书的形式展示出来。有兴趣

的可以进群看一看视频教学和录播

今天给你介绍一个好东西,可以让你摆脱正则的噩梦,那就是 Python 中一个非常冷门的库 -- 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,arp,in_port="tapbbdf080b-c2" actions=resubmit(,24)

复制代码

```

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

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

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

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

[图片上传失败...(image-fa4113-1610429647113)]

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

```

$ python -m pip install parse

复制代码

```

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

## 2\. parse 的结果

parse 的结果只有两种结果:

1.  没有匹配上,parse 的值为None

```

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

True

>>>

复制代码

```

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

```

>>> parse("hello", "hello world")

>>> parse("hello", "hello")

>>>

复制代码

```

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

```

>>> profile = parse("I am {}, {} years old, {}", "I am Jack, 27 years old, male")

>>> profile

>>> 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

>>> 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")

>>>

>>> pattern.parse("I am Tom, 26 years old, 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

>>> type(profile["age"])

复制代码

```

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

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

匹配时间

```

>>> parse('Meet at {:tg}', 'Meet at 1/2/2011 11:00 PM')

复制代码

```

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

| Type | Characters Matched | Output |

| :-- | :-- | :-- |

| l | Letters (ASCII) | str |

| w | Letters, numbers and underscore | str |

| W | Not letters, numbers and underscore | str |

| s | Whitespace | str |

| S | Non-whitespace | str |

| d | Digits (effectively integer numbers) | int |

| D | Non-digit | str |

| n | Numbers with thousands separators (, or .) | int |

| % | Percentage (converted to value/100.0) | float |

| f | Fixed-point numbers | float |

| F | Decimal numbers | Decimal |

| e | Floating-point numbers with exponent e.g. 1.1e-10, NAN (all case insensitive) | float |

| g | General number format (either d, f or e) | float |

| b | Binary numbers | int |

| o | Octal numbers | int |

| x | Hexadecimal numbers (lower and upper case) | int |

| ti | ISO 8601 format date/time e.g. 1972-01-20T10:21:36Z (“T” and “Z” optional) | datetime |

| te | RFC2822 e-mail format date/time e.g. Mon, 20 Jan 1972 10:21:36 +1000 | datetime |

| tg | Global (day/month) format date/time e.g. 20/1/1972 10:21:36 AM +1:00 | datetime |

| ta | US (month/day) format date/time e.g. 1/20/1972 10:21:36 PM +10:30 | datetime |

| tc | ctime() format date/time e.g. Sun Sep 16 01:03:52 1973 | datetime |

| th | HTTP log format date/time e.g. 21/Nov/2011:00:07:11 +0000 | datetime |

| ts | Linux system log format date/time e.g. Nov 9 03:37:44 | datetime |

| tt | Time e.g. 10:21:36 PM -5:30 | time |

## 5\. 提取时去除空格

去除两边空格

```

>>> parse('hello {} , hello python', 'hello     world    , hello python')

>>>

>>>

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

复制代码

```

去除左边空格

```

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

复制代码

```

去除右边空格

```

>>> parse('hello {:

复制代码

```

## 6\. 大小写敏感开关

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

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

```

>>> parse('SPAM', 'spam')

>>> parse('SPAM', 'spam') is None

False

>>> parse('SPAM', 'spam', case_sensitive=True) is None

True

复制代码

```

## 7\. 匹配字符数

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

```

>>> parse('{:.2}{:.2}', 'hello')  # 字符数不符

>>>

>>> parse('{:.2}{:.2}', 'hell')   # 字符数相符

复制代码

```

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

```

>>> parse('{:.2}{:2}', 'hello')

>>>

>>> parse('{:2}{:2}', 'hello')

复制代码

```

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

```

>>> parse('{:2}{:2}', '1024')

>>>

>>>

>>> parse('{:2d}{:2d}', '1024')

复制代码

```

## 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")

>>> type(_[0])

>>>

复制代码

```

其等价于

```

>>> def myint(string):

...     return int(string)

...

>>>

>>>

>>> parse("I am {:myint}", "I am 27", dict(myint=myint))

>>> type(_[0])

>>>

复制代码

```

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

```

>>> def shouty(string):

...    return string.upper()

...

>>> parse('{:shouty} world', 'hello world', dict(shouty=shouty))

>>>

复制代码

```

## 10 总结一下

parse 库在字符串解析处理场景中提供的便利,肉眼可见,上手简单。

在一些简单的场景中,使用 parse 可比使用 re 去写正则开发效率不知道高几个 level,用它写出来的代码富有美感,可读性高,后期维护起代码来一点压力也没有。

关于底层是如何实现的,是不是依赖正则,咱也不清楚。

速度上没有测试,目测不会比正则快。但是 parse 本身适用的场景就比较特殊,它适用于格式规范的小文本解析,如果要解析大文本,建议还是正则搞起吧。

原文链接:https://juejin.cn/post/6869911894153494536

### 回答1: 你好,我是 C 知道。关于你的问题,我可以回答。要用 Python 写一个文本检测程序,可以使用 Python正则表达式模块 re,或者使用第三方如 nltk、spaCy 等。通过对文本进行分词、词性标注、命名实体识别等处理,可以实现文本的检测和分类。希望这个回答能够帮到你。 ### 回答2: 要用Python写一个文本检测程序,可以使用正则表达式和字符串处理的方法来实现。 首先,需要定义一个函数,用于接收用户输入的文本作为参数,然后进行检测。在函数内部,我们可以使用正则表达式来匹配敏感词汇或不良内容。 可以创建一个包含敏感词的列表,然后使用正则表达式中的re模块来匹配文本中是否包含这些词汇。可以使用re模块中的search()方法来查找匹配项,并返回第一个匹配结果。 例如: ```python import re def text_detection(text): sensitive_words = ['敏感词1', '敏感词2', '敏感词3'] # 包含敏感词的列表 for word in sensitive_words: pattern = re.compile(word, re.IGNORECASE) # 忽略大小写 match = re.search(pattern, text) if match: return '文本包含敏感词' return '文本正常' # 测试 text = input('请输入文本:') result = text_detection(text) print(result) ``` 这个程序中,用户需要输入文本,然后调用text_detection()函数来进行检测。函数会遍历包含敏感词的列表,用正则表达式搜索匹配结果。如果匹配到敏感词,会返回'文本包含敏感词',否则返回'文本正常'。 以上就是一个简单的用Python编写的文本检测程序。当然,实际应用中还可以根据需求进行进一步的优化和扩展。 ### 回答3: 文本检测程序是一种通过计算机自动分析文本内容,判断其中是否含有不良信息或违规内容的工具。下面我将介绍一种使用Python编写文本检测程序的方法。 首先,我们需要收集一批包含正常和不良内容的文本样本,并进行标记。这些样本可以是包含敏感词汇、违规内容或其他不良信息的文本。这些样本将作为我们模型训练的依据。 接下来,我们将使用Python中的自然语言处理,如NLTK或SpaCy来对文本进行处理和分析。我们可以使用这些中的函数和方法来进行文本清洗、标记化、分词和词性标注等操作。 然后,我们需要选择一个适当的机器学习算法来训练我们的模型。常见的算法包括朴素贝叶斯分类器、支持向量机、决策树等。我们可以使用Python中的机器学习,如scikit-learn来实现这些算法。 在训练模型之后,我们可以使用模型来对新的文本进行分类。具体而言,我们可以提取文本的特征,并将这些特征输入到模型中进行预测。如果模型给出的预测结果超过了我们设定的阈值,则可以认定该文本为不良内容。 最后,我们可以根据预测结果进行相应的处理。例如,把包含不良内容的文本标记为违规,并进行删除或阻止展示。 需要注意的是,文本检测程序需要不断的优化和更新。我们可以定期收集新的样本进行模型的重新训练,以提高模型的准确性和鲁棒性。同时,我们还可以使用其他的技术手段,如深度学习、自定义规则等来进一步提升文本检测程序的效果。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值