如何从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在
^{pr2}$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
虽然Martijn Pieters does a very good job在解释如何改进代码时,我建议采用完全不同的方法,即使用Monadic Parser Combinator库,例如Parcon。这允许您超越上下文无关语法,并在运行时根据当前解析过程提取的信息轻松修改解析器:
结果:
^{2}$一开始这有点让人心神不宁,就像所有的东西都是一元的。但是表达的灵活性和简洁性是值得花时间学习单子的。在
你的错误很多,以下是我目前发现的错误:
行
numSims = (int)line
并不像您所想的那样。Python没有C类型转换,您需要调用类型int
类型:稍后,您可以使用大写字母
^{2}$Int
来复合此错误:以类似的方式纠正:
由于
.split()
的默认值是在空格上拆分,所以可以省略" "
参数。更好的是,将它们组合成一行:您从不递增
k
,因此您的while k < numSims:
循环将永远继续,因此您将得到一个EOF错误。请改用for
循环:您不需要在这个函数的任何地方使用
while
,它们都可以被for variable in xrange(upperlimit):
循环代替。Python字符串没有
.charAt
方法。使用[index]
代替:但是由于
myLine[j] == 'A'
是一个布尔测试,您可以像这样简化Spot()
实例化:在Python中不需要太多地初始化变量。如果在下一行上分配一个新值,则可以获得
numSims = 0
和col = 0
行的大部分内容。创建一个'myMap
variable but then ignore it by referring to
cls.myMap文件`相反。在这里没有任何地图文件覆盖前面的地图。
重写版本:
相关问题 更多 >
编程相关推荐