Python 正则表达式:返回包含给定子字符串的单词列表 [英] Python regexes: return a list of words containing a given substring

查看:31
本文介绍了Python 正则表达式:返回包含给定子字符串的单词列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

什么是基于正则表达式的函数 f ,给定输入文本和字符串,返回文本中包含该字符串的所有单词.例如:

What would be a function f based on regexes that, given an input text and a string, returns all the words containing this string in the text. For example:

f("This is just a simple text to test some basic things", "si")

会回来:

["simple", "basic"]

(因为这两个词包含子串"si")

(because these two words contain the substring "si")

怎么做?

推荐答案

我不相信没有比我的方法更好的方法了,但类似于:

I'm not convinced there isn't a better way to do this than my approach, but something like:

import re

def f(s, pat):
    pat = r'(\w*%s\w*)' % pat       # Not thrilled about this line
    return re.findall(pat, s)


print f("This is just a simple text to test some basic things", "si")

作品:

['simple', 'basic']

这篇关于Python 正则表达式:返回包含给定子字符串的单词列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆