【发布时间】:2012-09-26 22:57:54
【问题描述】:
如何在python中逐行读取并解析文件?
我是 python 新手。
输入的第一行是模拟次数。 下一行是行数 (x),后跟一个空格,然后是列数 (y)。 下一组 y 行将有 x 个字符,其中一个句点 ('.') 代表一个空格,一个大写字母“A”代表一个起始代理。
我的代码出错了
Traceback (most recent call last):
numSims = int (line)
TypeError: int() argument must be a string or a number, not 'list'
感谢您的帮助。
输入.txt
2 --- 2 simulations
3 3 -- 3*3 map
.A. --map
AA.
A.A
2 2 --2*2 map
AA --map
.A
def main(cls, args):
numSims = 0
path = os.path.expanduser('~/Desktop/input.txt')
f = open(path)
line = f.readlines()
numSims = int (line)
print numSims
k=0
while k < numSims:
minPerCycle = 1
row = 0
col = 0
xyLine= f.readLines()
row = int(xyLine.split()[0])
col = int(xyLine.split()[1])
myMap = [[Spot() for j in range(col)] for i in range(row)]
## for-while
i = 0
while i < row:
myLine = cls.br.readLines()
## for-while
j = 0
while j < col:
if (myLine.charAt(j) == 'B'):
cls.myMap[i][j] = Spot(True)
else:
cls.myMap[i][j] = Spot(False)
j += 1
i += 1
对于 Spot.py
Spot.py
class Spot(object):
isBunny = bool()
nextCycle = 0
UP = 0
RIGHT = 1
DOWN = 2
LEFT = 3
SLEEP = 4
def __init__(self, newIsBunny):
self.isBunny = newIsBunny
self.nextCycle = self.UP
【问题讨论】:
-
那么,给出的代码有什么问题?
-
你应该试试 atpy 模块——它很容易读入和解析列,你所要做的就是指定文件类型(在这种情况下为 ascii)和分隔符。
-
@Mike:关于你的 Spot 类......我认为你仍然对 Python 类的工作方式有误解。请不要试图伪造变量的类型声明,它们既不需要也不能阻止,例如这个:
s = Spot(7); s.isBunny = 'joe'