閱讀XY COORDS我有存儲在以下格式號的文本文件:Python從文本文件
93 407 77 400 94 365 109 372
135 312 180 328
100 120 140 160
我想這些值放入兩個列表。一個用於多邊形,一個用於矩形。
如果一行中有8個數字,則存儲到多邊形列表中。如果一行中有4個數字,則它會存儲在矩形列表中。像這樣
polygon=[ [93, 407, 77, 400, 94, 365, 109, 372] ]
rectangle=[ [135, 312, 180, 328,], [100, 120, 140, 160] ]
然後,我會使用這些值繪製無論是矩形或畫布上的多邊形。
這裏是我的代碼是什麼至今:
class getXYCoords:
def __init__(self, textFile):
self.textFile = textFile
polygon = []
rectangle = []
with open(self.textFile) as f:
for line in f:
line = line.split() #strip EOL
if line: #lines (ie skip them)
# Stores values into polygon list
if len(line) == 8:
line = [int(i) for i in line]
polygon.append(line)
# Stores values into rectangle list
elif len(line) == 4:
line = [int(i) for i in line]
rectangle.append(line)
return polygon, rectangle
# Example program
if __name__ == '__main__':
#polygon = []
#rectangle = []
# Get XY coordinates
polygon, rectangle = getXYCoords('HAMH HUTC XY.txt')
print(polygon,'\n')
print(rectangle)
當我運行程序我得到這個錯誤信息:
line 46 in module
polygon, rectangle = getXYCoords('HAMH HUTC XY.txt')
TypeError: init() should return None, not 'tuple'
錯誤信息非常清晰...您對此有何瞭解?你有沒有理由使用類而不是函數? –
我想把這段代碼放在一個單獨的python文件中,並且認爲我需要這樣做。 – goofenhour