在python中解析文本

2024-04-25 23:45:26 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个这样结构的文本文件

1\t        13249\n

2\t        3249\n

3\t        43254\n

etc...

这是一个非常简单的清单。我把文件打开了,我能读到行。我有以下代码:

^{pr2}$

我想做的是将每行的第一个数赋给一个变量(比如xi),并将每行的第二个数赋给另一个变量(yi)。我们的目标是能够对这些数字进行统计。在

提前致谢。在


Tags: 文件代码目标etc数字结构文本文件yi
3条回答
count = 0
for x in open(filename):
   # strip removes all whitespace on the right (so the newline in this case)
   # split will break a string in two based on the passed parameter
   xi, yi = x.rstrip().split("\t") # multiple values can be assigned at once
   count += 1
return count

不需要重新发明轮子。。在

import numpy as np

for xi, yi in np.loadtxt('blah.txt'):
    print(xi)
    print(yi)
>>> with open('blah.txt') as f:
...     for i,xi,yi in ([i]+map(int,p.split()) for i,p in enumerate(f)):
...             print i,xi,yi
... 
0 1 13249
1 2 3249
2 3 43254

注意int('23\n')=23

这一点更清楚: 请注意,enumerate提供了一个包含计数器的生成器。在

^{pr2}$

相关问题 更多 >