【学习python】re 正则表达式匹配特定词性的conll,提取句子主干(主谓宾)

本文演示了如何使用Python的re模块进行正则表达式匹配,从文本中提取特定的中文字符。通过不同的正则模式,匹配汉字、数字、字母等,并展示了如何提取句子中的名词、动词、代词等。
摘要由CSDN通过智能技术生成

------------------找寻特定内容-------------------------------

>>> # -*- coding: utf-8 -*-

>>> import re
>>> pattern = re.compile(u'[白蓝绿黄][A-Z][A-Z0-9]{5}')
>>> match = pattern.match(u'白A1B2C3')
>>> if match:
...   print('OK')
... else:
...   print('NO')
...
OK

>>>

-------------------------------------------------------------------

>>> pattern = re.compile(u'[白蓝绿黄]?\d')
>>> match = pattern.match(u'白1')
>>> if match:
...   print('OK')
... else:
...   print('NO')
...
OK
>>> match = pattern.match(u'白')
>>> if match:
...   print('OK')
... else:
...   print('NO')
...
NO

>>>

----------------------------------------------------------------------

>>> f = open('E:/abc.txt').read()
>>> import re
>>> pattern = re.compile(r'\S')
>>> match = patter.match(f)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'patter' is not defined
>>> match = pattern.match(f)
>>> print(match)
<_sre.SRE_Match object; span=(0, 1), match='1'>

-----------------------------------------------------------------

>>> print(match.group())
1

>>>

---------------------------------------------------------------

>>> pattern = re.compile(r'\w')
>>> f = open('E:/abc.txt').read()
>>> match = pattern.match(f)
>>> print(match)
<_sre.SRE_Match object; span=(0, 1), match='1'>

>>>

------------------------------------------------------------

>>> match = r'\d'
>>> f = open('E:/abc.txt').read()
>>> z = re.search(match,f).group()
>>> print(z)
1

>>>

----------------------------------------------------------

>>> match = r'[\u4e00-\u9fa5]'
>>> f = open('E:/abc.txt').read()
>>> z = re.search(match,f).group()
>>> print(z)

>>>

---------------------------------------

>>> match = r'[\u4e00-\u9fa5]*'
>>> f = open('E:/abc.txt').read()
>>> z = re.search(match,f).group()
>>> print(z)


>>> match = r'[\u4e00-\u9fa5]+'
>>> f = open('E:/abc.txt').read()
>>> z = re.search(match,f).group()
>>> print(z)
徐先生

>&g

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值