繁体   English   中英

Python 正则表达式:返回包含给定子字符串的单词列表

[英]Python regexes: return a list of words containing a given substring

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

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

会返回:

["simple", "basic"]

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

怎么做?

对于这样的事情,我不会使用正则表达式,我会使用这样的东西:

def f(string, match):
    string_list = string.split()
    match_list = []
    for word in string_list:
        if match in word:
            match_list.append(word)
    return match_list

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

我不相信没有比我的方法更好的方法来做到这一点,但类似于:

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

这是我对解决方案的尝试。 我用“”分割输入字符串,然后尝试将每个单独的单词与模式匹配。 如果找到匹配项,则将该词添加到结果集中。

import re

def f(str, pat):
    matches = list()
    str_list = str.split(' ');

    for word in str_list:
        regex = r'' + re.escape(word)
        match = re.search(regex, word)
        if match:
            matches.append(word)
    return matches

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

def func(s, pat):
    pat = r'\b\S*%s\S*\b' % re.escape(pat) 
    return re.findall(pat, s)


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

你需要这个 。 \\b将通过在单词边界处切割来仅取出单词。 \\S不会选择任何space

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM