如何从python文件中逐行读取和解析?

2024-09-28 05:19:03 发布

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

如何从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

Tags: pathselfforline代表colintrow
2条回答

虽然Martijn Pieters does a very good job在解释如何改进代码时,我建议采用完全不同的方法,即使用Monadic Parser Combinator库,例如Parcon。这允许您超越上下文无关语法,并在运行时根据当前解析过程提取的信息轻松修改解析器:

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))

结果:

^{2}$

一开始这有点让人心神不宁,就像所有的东西都是一元的。但是表达的灵活性和简洁性是值得花时间学习单子的。在

你的错误很多,以下是我目前发现的错误:

  1. numSims = (int)line并不像您所想的那样。Python没有C类型转换,您需要调用类型int类型:

    numSims = int(line)
    

    稍后,您可以使用大写字母Int来复合此错误:

    ^{2}$

    以类似的方式纠正:

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

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

    row, col = map(int, xyLine.split())
    
  2. 您从不递增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 = 0col = 0行的大部分内容。

  5. 创建一个'myMapvariable 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)

相关问题 更多 >

    热门问题