设为首页收藏本站

Crossin的编程教室

 找回密码
 立即加入
12
返回列表 发新帖
楼主: Tony
打印 上一主题 下一主题

使用正则表达式匹配单词

[复制链接]

7

主题

0

好友

127

积分

注册会员

Rank: 2

11#
发表于 2016-11-5 09:25:47 |只看该作者
本帖最后由 Tony 于 2016-11-5 09:30 编辑
crossin先生 发表于 2016-11-4 14:18
输出
['roads', 'must', 'a', 'man', 'walk', 'they', 'call', 'him', 'a', 'man', 'a', 'is', 'blowing' ...

我是这样写的:

  1. import re
  2. PATH = r'C:\Users\Tony\Desktop\Demo\demo.txt'
  3. s= open(PATH)
  4. file_read = s.read()

  5. words = re.findall(r'(?<=\s)[A-z]+(?=\s|$)|^[A-z]+', file_read)
  6. print words
复制代码
结果:
  1. ['Ho', 'roads', 'must', 'a', 'man', 'walk', 'they', 'call', 'him', 'a', 'man', 'a', 'is', 'blowing', 'in', 'the', 'wind', 'The', 'answer', 'is', 'blow', 'in', 'the']
复制代码
demo.txt 的内容是这些:

Ho454w m545any roads must a man walk downBef434ore they call him a man
H767ow m767any s767eas m676ust a wh453ite do4543ve sai45l
Be56fore s565he sle3434eps i343n th434e san453d
Ho343w man565y tim5767es m767ust t78he cann564on ba45lls f656ly
Be686fore the7876y're f787orever ba7878nned
T7567he an75675swer m76y fr656iend is blowing in the wind
The answer is blow .ing in the wi1n3d

回复

使用道具 举报

174

主题

45

好友

11万

积分

管理员

Rank: 9Rank: 9Rank: 9

12#
发表于 2016-11-5 22:05:27 |只看该作者
Tony 发表于 2016-11-5 09:25
我是这样写的:结果:demo.txt 的内容是这些:

Ho454w m545any roads must a man walk downBef434ore the ...

r='(?<=\s)[A-z]+(?=\s|$)|^[A-z]+(?=\s|$)'
#==== Crossin的编程教室 ====#
微信ID:crossincode
网站:http://crossincode.com
回复

使用道具 举报

7

主题

0

好友

127

积分

注册会员

Rank: 2

13#
发表于 2016-11-6 08:54:01 |只看该作者
crossin先生 发表于 2016-11-5 22:05
r='(?

现在可以了,谢谢crossin先生!
看来我还要努力学习正则表达式啊,你说的这个零宽断言,我以前根本没有听说过,涨了见识了!
回复

使用道具 举报

174

主题

45

好友

11万

积分

管理员

Rank: 9Rank: 9Rank: 9

14#
发表于 2016-11-6 22:02:37 |只看该作者
Tony 发表于 2016-11-6 08:54
现在可以了,谢谢crossin先生!
看来我还要努力学习正则表达式啊,你说的这个零宽断言,我以前根本没有听 ...

你这个需求确实不太好写。

推荐看看这个 http://deerchao.net/tutorials/regex/regex-1.htm
#==== Crossin的编程教室 ====#
微信ID:crossincode
网站:http://crossincode.com
回复

使用道具 举报

7

主题

0

好友

127

积分

注册会员

Rank: 2

15#
发表于 2016-11-9 09:01:56 |只看该作者
crossin先生 发表于 2016-11-6 22:02
你这个需求确实不太好写。

推荐看看这个 http://deerchao.net/tutorials/regex/regex-1.htm

我刚好搜到了,谢谢!
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即加入

QQ|手机版|Archiver|Crossin的编程教室 ( 苏ICP备15063769号  

GMT+8, 2024-5-9 00:58 , Processed in 0.024911 second(s), 20 queries .

Powered by Discuz! X2.5

© 2001-2012 Comsenz Inc.

回顶部