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 f开发者_运维知识库or all the values.
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.
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
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.
精彩评论