2

如何逐行读取并从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

现货.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
4

2 回答 2

7

您的错误很多,这是我迄今为止发现的错误:

  1. 这条线numSims = (int)line没有做你认为它做的事情。Python 没有 C 类型转换,您需要改为调用类型int

    numSims = int(line)
    

    您稍后通过使用大写拼写来复合此错误Int

    row = (Int)(xyLine.split(" ")[0])
    col = (Int)(xyLine.split(" ")[1])
    

    以类似的方式更正这些:

    row = int(xyLine.split()[0])
    col = int(xyLine.split()[1])
    

    并且由于默认.split()是在空格上拆分,因此您可以省略该" "参数。更好的是,将它们组合成一行:

    row, col = map(int, xyLine.split())
    
  2. 你永远不会 increment k,所以你的while k < numSims:循环将永远持续下去,所以你会得到一个 EOF 错误。改用for循环:

    for k in xrange(numSims):
    

    你不需要while在这个函数的任何地方使用,它们都可以用for variable in xrange(upperlimit):循环替换。

  3. Python 字符串没有.charAt方法。改用[index]

    if myLine[j] == 'A':
    

    但由于myLine[j] == 'A'是布尔测试,您可以Spot()像这样简化您的实例化:

    for i in xrange(row):
        myLine = f.readLine()
        for j in xrange(col):
            cls.myMap[i][j] = Spot(myLine[j] == 'A')
    
  4. 在 Python 中不需要太多初始化变量。如果您在下一行分配新值,您可以获得大部分numSims = 0和行等。col = 0

  5. 您改为创建一个“myMap variable but then ignore it by referring tocls.myMap”。

  6. 这里没有处理多重映射;文件中的最后一个地图将覆盖任何前面的地图。

改写版:

def main(cls, args):
    with open(os.path.expanduser('~/Desktop/input.txt')) as f:
        numSims = int(f.readline())
        mapgrid = []
        for k in xrange(numSims):
            row, col = map(int, f.readline().split())  
            for i in xrange(row):
                myLine = f.readLine()
                mapgrid.append([])
                for j in xrange(col):
                    mapgrid[i].append(Spot(myLine[j] == 'A'))
         # store this map somewhere?
         cls.myMaps.append(mapgrid)
于 2012-09-26T23:01:42.977 回答
1

虽然Martijn Pieters在解释如何使您的代码变得更好方面做得非常好,但我建议采用完全不同的方法,即使用像 Parcon 这样的Monadic Parser Combinator库。这允许您超越上下文无关语法,并在运行时根据当前解析过程提取的信息轻松修改解析器:

from functools import partial
from parcon import (Bind, Repeat, CharIn, number, End,
                    Whitespace, ZeroOrMore, CharNotIn)

def array(parser, size):
    return Repeat(parser, min=size, max=size)

def matrix(parser, sizes):
    size, sizes = sizes[0], sizes[1:]
    return array(matrix(parser, sizes) if sizes else parser, size)

comment = '-' + ZeroOrMore(CharNotIn('\n')) + '\n'

sims = Bind(number[int],
            partial(array,
                    Bind(number[int] + number[int],
                         partial(matrix,
                                 CharIn('.A')['A'.__eq__])))) + End()

text = '''
2   --- 2 simulations
3 3  -- 3*3 map
.A.  --map
AA.
A.A
2 2  --2*2 map
AA  --map
.A
'''

import pprint
pprint.pprint(sims.parse_string(text, whitespace=Whitespace() | comment))

结果:

$ python numsims.py
[[False, True, False], [True, True, False], [True, False, True]]
[[True, True], [False, True]]

起初,它有点让人费解,就像所有单子的东西一样。但是表达的灵活性和简洁性非常值得花时间学习单子。

于 2012-09-27T01:03:13.333 回答