Search code examples
python-2.7recursive-descent

Python:How can you recursively search a .txt file, find matches and print results


I have been searching for an answer to this, but can not seem to get what I need. I would like a python script that reads my text file and starting from the top working its way through each line of the file and then prints out all the matches in another txt file. Content of the text file is just 4 digit numbers like 1234. example 1234 3214 4567 8963 1532 1234 ...and so on. I would like the output to be something like: 1234 : matches found = 2 I know that there are matches in the file do to almost 10000 lines. I appreciate any help. If someone could just point me in the right direction here would be great. Thank you.


Solution

  • Thanks to everyone who helped me on this. Thank you to @csabinho for the code he provided and to @IanAuld for asking me "Why do you think you need recursion here?" – IanAuld. It got me to thinking that the solution was a simple one. I just wanted to know which 4 digit numbers had duplicates and how many, and also which 4 digit combos were unique. So this is what I came up with and it worked beautifully!

    import re
    
    a=999
    while a <9999:
    a = a+1
    
    file = open("4digits.txt", 'r')
    fileContent = file.read()
    
    pattern = str(a)
    result = len(re.findall(pattern, fileContent))
    if result >= 1:
        print(a,"matches",result)
    else:
        print (a,"This number is unique!")