如何在python中拆分连接词

2024-10-01 13:24:59 发布

您现在位置:Python中文网/ 问答频道 /正文

我想计算植物在文本文件中出现的次数。然而,一些工厂实例显示为:

Floweredplants or plantdaisy. 

如何使用regexp拆分上述单词并用“plant”替换它们


Tags: or实例工厂单词次数植物regexp文本文件
3条回答

你可以做:

if s.find("plant") >= 0:
    print "It contains plant"

这将只测试“plant”是否是s的子字符串(如果参数不在字符串中,则find返回-1)。这就是你要找的吗?你知道吗

您可以使用一些简单的正则表达式来匹配所有可能的情况,例如:

import re
re.search('[A-Za-z]*plants?', 'floweredplants')

使用边界:

\bplant\w*         # will match 'plantation'
\w*plant\b         # will match 'eleplant'
\w*plant\w*        # will match any of previous examples and 'eleplanted'
\bplant\b          # will match only exactly 'plant' words

希望有帮助。你知道吗

相关问题 更多 >