Apps
Apps

Reputation: 549

How do I search for integer (x,y) in a textfile using python?

I have a matrix stored in a textfile as:

(i, j)      count

I need to search for the pair (i,j). How do I do that?

with open("matrix.txt","r") as searchmat:            
        for line in searchmat:
                word=str((x,y))
                if word in line:
            t=line.split('\t')
            f=t[1]
                return f

I am getting NONE for all the values.

Upvotes: 1

Views: 135

Answers (3)

Shawn Chin
Shawn Chin

Reputation: 86894

The code looks fine (assuming you got your indentations right). Maybe there is an issue with your data file format. More than one tab character in the separator perhaps? Try using t=line.split() instead.

Upvotes: 1

phimuemue
phimuemue

Reputation: 35993

This might help:

def reader(path):
    import re
    pattern = re.compile("^\((\d*), (\d*)\).*$")
    with open(path) as searchmat:
        for line in searchmat:
            print re.match(pattern, line).group(1, 2)   # print both raw groups
            print int(re.match(pattern, line).group(1)) # first number as int
            print int(re.match(pattern, line).group(2)) # second number as int

It traverses the file given by path and looks in each line for the pattern you described.

Upvotes: 0

Chinmay Kanchi
Chinmay Kanchi

Reputation: 65923

Looks like you have messed up indentation. From looking at the code you've (I assume) pasted here, it looks like you have mixed tabs and spaces, which Python most definitely does not like. Replace all tabs in your file with spaces, and indent your code so it looks like this:

with open("matrix.txt","r") as searchmat:            
    for line in searchmat:
        word=str((x,y))
        if word in line:
            t=line.split('\t')
            f=t[1]
            return f

Upvotes: 0

Related Questions