如何使用 python 在文本文件中搜索整数 (x,y)?
我有一个存储在文本文件中的矩阵:
(i, j) count
我需要搜索 (i,j) 对。我该怎么做?
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
对于所有值,我都得到NONE。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
代码看起来不错(假设你的缩进正确)。也许您的数据文件格式有问题。分隔符中可能有多个制表符吗?尝试使用
t=line.split()
代替。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.看来你弄乱了缩进。从你(我假设)粘贴到这里的代码来看,看起来你混合了制表符和空格,这是 Python 绝对不喜欢的。将文件中的所有制表符替换为空格,并缩进代码,如下所示:
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:
这可能会有所帮助:
它遍历
path
给出的文件,并在每一行中查找您所描述的模式。This might help:
It traverses the file given by
path
and looks in each line for the pattern you described.