Searching for a wildcard pattern in a text file in Python

1.1k Views Asked by At

I am trying to search for similar words in Python given a wildcard pattern, for example in a text file similar to a dictionary- I could search for r?v?r? and the correct output would be words such as 'rover', 'raver', 'river'. This is the code I have so far but it only works when I type in the full word and not the wildcard form.

name = input("Enter the name of the words file:\n"
pattern = input("Enter a search pattern:\n")`

textfile = open(name, 'r')
filetext = textfile.read()
textfile.close()
match = re.findall(pattern, filetext)
if match is True:
    print(match)
else:
    print("Sorry, matches for ", pattern, "could not to be found")
1

There are 1 best solutions below

4
Arush Srivastava On

Use dots for blanks

name = input("Enter the name of the words file:\n"
pattern = input("Enter a search pattern:\n")`

textfile = open(name, 'r')
filetext = textfile.read()
textfile.close()
re.findall('r.v.r',filetext)
if match is True:
    print(match)
else:
    print("Sorry, matches for ", pattern, "could not to be found")

Also, match is a string, so you want to do if match!="" or if len(match)>0 ,whichever one suits your code.