Home > Software design >  Python Function that Match a Given Template
Python Function that Match a Given Template

Time:02-08

Say I have a template and I have a dictionary containing words. I want to create a function that returns a list of words that match the given template. To illustrate this:

template = 'W**ER'
dictionary = {'apple': '', 'water': '', 'weber': '', 'tiger': '', 'elder': '', 'rover': '', 'waver': ''}


Desired output:
output_list = ['water', 'weber', 'waver']

I'm not entirely sure how to create the function and I would totally appreciate any help. Thanks!

CodePudding user response:

You can use regular expression to find a matched keys with the templete.

My code find all the matched keys, and it is case-insensitive code, as follows:

import re

dictionary = {'apple': '', 'wter': '', 'weber': '', 'tiger': '', 'elder': '', 'rover': '', 'waver': ''}

output = []
for key in dictionary.keys():
    matched = re.match("[Ww] ..[Ee] [Rr] ", key) # case-insensitive, 5 letters
    if matched:
        output.append(key)

print(output)
#['water', 'weber', 'waver']

For more information about regular expressions with examples, you can see: https://docs.python.org/3/library/re.html

CodePudding user response:

Here is a working solution

import re

dictionary = {'apple': '', 'water': '', 'weber': '', 'tiger': '', 'elder': '', 'rover': '', 'waver': ''}
keys = list(dictionary.keys()) # not necessary but I think it's cleaner

output_list = [key for key in keys if re.search(r'^w..er$', key)] 

First ^ assert this is the beginning of your word (prevent word that would not start with w but still have this pattern inside), re.match does it by default, . correspond to any character and $ as for ^ assert you touch the end of the string (here, the word).

CodePudding user response:

As all the answers contain '.' as any symbol, although it may be better to use any letter instead. Also note having start of string and end of string. That means that waterdasdadad won't proceed

Here is my code

import re

template = r'^w\w\wer$'  # means start of string, w, any alphabet char twice, e, r, end of string
regex = re.compile(template)
dictionary = {'apple': '', 'water': '', 'weber': '', 'tiger': '', 'elder': '', 'rover': '', 'waver': ''}

output_list = list()

for key in dictionary:
    if regex.fullmatch(key):  # use key.lower() for case insensitivity
        output_list.append(key)

print(output_list)

CodePudding user response:

Try to use regex:

import re
ptrn = re.compile("w..er")
list(filter(lambda key: re.match(ptrn, key), dictionary))

CodePudding user response:

Try this:

import re

def matching(dic, pat):
    result = [i for i in dic if re.match(pat, i)]
    return result

pattern = 'w\w*er'
dictionary = {'apple': '', 'water': '', 'weber': '', 'tiger': '', 'elder': '', 'rover': '', 'waver': ''}

print(matching(dictionary, pattern))
  •  Tags:  
  • Related