Johny
Johny

Reputation: 129

Check if there are multiple matches in a file in Python

The user enters data. The data is checked through all line of a file. If what he enters corresponds to a line, it is printed.

If the results are more than one, I'd like to loop the entry process until the user refines his choice enough so that only one outcome is found. What can I use where 'mutipleAnswersAreFound'?

My code:

def search()
    with open("file.txt") as f:
        nameSearch = str(raw_input("Enter first name, last name, email, or phone: "))
        for line in f: 
            if nameSearch in line: 
                print line
            else if 'mutipleAnswersAreFound' :
                search()

Upvotes: 2

Views: 100

Answers (3)

Milor123
Milor123

Reputation: 555

I think that you could use regular expressions, import re in python. for example:

import re
expression = re.compile('(wordto)')
example = ' hi worldto, how are wordto xD wordto'
matches = expression.findall(example)
if matches:
    print matches
    print 'the count is', len(matches)

>>>['wordto', 'wordto']
>>>the count is 2

Upvotes: 0

xvan
xvan

Reputation: 4855

Wrap it in an infinite loop, break it when match count is lower or equal to 1.

def search()
  while True:
    count=0
    with open("file.txt") as f:
      nameSearch = str(raw_input("Enter first name, last name, email, or phone: "))
      for line in f: 
        if nameSearch in line: 
            print line
            count+=1
      if count > 1 :
        print 'Multiple matches, please refine your search'
      else: 
        break

Upvotes: 0

Banach Tarski
Banach Tarski

Reputation: 1829

line.count(nameSearch) will return the number of times nameSearch appears in the string line. If this count is more than 1 then you have your elif case.

eg

"aaa".count("aa") will return 2 since we have two occurrences of the string "aa"

Your code will look something like

cnt = line.count(nameSearch)
if cnt == 1:
    print line
elif cnt > 1:
    search()

If you want the occurrences to be delimited by a space then you can do this

words = line.split()
cnt = 0
for word in words:
    if nameSearch == word: cnt += 1
    if cnt > 1: break
if cnt == 1:
     print line
elif cnt > 1:
     search()

Upvotes: 1

Related Questions