![](/img/trans.png)
[英]I try to parse line by line within a text file in Python , but it just can parse first line, it can not read from second line
[英]How to read line by line and parse from a file in 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'
謝謝你的幫助。
INPUT.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
你的錯誤很多,這是我迄今為止發現的錯誤:
行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())
你永遠不會增加k
,所以你的while k < numSims:
循環將永遠繼續,所以你會得到一個EOF錯誤。 改為使用for
循環:
for k in xrange(numSims):
你並不需要使用while
在此功能中的任何地方,他們都可以被替換為for variable in xrange(upperlimit):
循環。
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')
在Python中沒有必要非常初始化變量。 如果要在以下行上分配新值,則可以獲得大多數numSims = 0
和col = 0
行等。
您創建了一個'myMap variable but then ignore it by referring to
cls.myMap`來variable but then ignore it by referring to
。
這里沒有處理多重地圖; 文件中的最后一個地圖將覆蓋任何前面的地圖。
改寫版:
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)
雖然Martijn Pieters在解釋如何更好地編寫代碼方面做得非常好,但我建議采用一種完全不同的方法,即使用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))
結果:
$ python numsims.py
[[False, True, False], [True, True, False], [True, False, True]]
[[True, True], [False, True]]
起初它有點像心靈纏繞,就像monadic一樣。 但表達的靈活性和簡潔性非常值得花時間學習單子。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.