使用文本文件中的属性创建对象

时间:2016-04-30 11:48:34

标签: python-3.x

我制作的程序可以从纺织品(名为30eapril.txt)读取一些足球队的信息,并在创建一些团队对象时使用这些数据。我想知道如何让程序读取纺织品中的团队数量并创建它们的对象。到目前为止我写的代码有效,但有很多重复的部分!

class team: 
    def __init__(self, teamdata):
        self.name = teamdata[0]
        self.wins = teamdata[1]
        self.drawn = teamdata[2]
        self.losses = teamdata[3]
    def __repr__(self): 
        return self.name.ljust(15) + '{} {} {}'.format(self.wins, self.drawn, self.losses)

laglista = []
with open('30eapril.txt', 'rt') as file:
    for line in file:
        laglista.append(line)

team1data = (laglista[0]).split()
team2data = (laglista[1]).split()
team3data = (laglista[2]).split()
team4data = (laglista[3]).split()

lag1 = team(team1data) 
lag2 = team(team2data)
lag3 = team(team3data)
lag4 = team(team4data)

print(lag1) 
print(lag2)
print(lag3)
print(lag4)

这就是文本文件中的内容

Arsenal        2 1 0 
Manchester     2 0 0 
Liverpool      0 1 2 
Newcastle      0 0 2 

希望有人可以提供帮助! //彼得

1 个答案:

答案 0 :(得分:2)

缩短代码:(当然可以更好)

#include "myHeaderGL.h"
#include <cstdlib>
#include <gl/GL.h>
#include <gl/GLU.h>// not used in this example

LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
{
    return window.WndProc(hWnd, message, wParam, lParam);
}

int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow)
{
    POINT windowPosition = { 100, 100 };
    POINT windowSize = { 800, 600 };
    if (!window.Initialize(hInstance, windowPosition, windowSize))
    {
        MessageBox(NULL, "Initialisation fail.", "OpenGL Application", MB_OK | MB_ICONERROR);
        return EXIT_FAILURE;
    }
    else return window.Run();

}

LRESULT Window::WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
{
    switch (message)
    {
    case WM_DESTROY:
        PostQuitMessage(0);
        break;
    case WM_PAINT:
        RECT rect;
        GetClientRect(hWnd, &rect);
        clientWidh = rect.right - rect.left;
        clientHeight = rect.bottom - rect.top;
        break;
    default:
        return(DefWindowProc(hWnd, message, wParam, lParam));
    }
    return 0L;
}

LRESULT WindowGL::WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
{
    long result = Window::WndProc(hWnd, message, wParam, lParam); 
    switch (message)
    {
    case WM_CREATE:
        if (!InitWGL(hWnd))
        {
            MessageBox(NULL, "Render context fail to load", "My OpenGL", MB_OK | MB_ICONERROR);
            return EXIT_FAILURE;
        }
        SetScene(false);
        break;
    case WM_DESTROY:
        DestroyWGL();
        break;
    case WM_SIZE:
        SetScene(false);
        break;
    case WM_PAINT:
        Render();
        ValidateRect(hWnd, NULL);
        break;
    //default: 
        //return (DefWindowProc(hWnd, message, wParam, lParam));
    }
    return result;
}

bool Window::Initialize(HINSTANCE appHandle, POINT windowPosition, POINT windowSize)
{
    char windowName[] = "My 1 OpenGL";

    WNDCLASSEX wc;
    wc.cbSize = sizeof(wc);
    wc.style = CS_HREDRAW | CS_VREDRAW | CS_OWNDC; 
    wc.lpfnWndProc = (WNDPROC)::WndProc; 
    wc.cbClsExtra = 0; 
    wc.cbWndExtra = 0; 
    wc.hInstance = appHandle; 
    wc.hIcon = NULL; 
    wc.hIconSm = NULL; 
    wc.hCursor = LoadCursor(NULL, IDC_ARROW); 
    wc.hbrBackground = NULL; 
    wc.lpszMenuName = NULL;
    wc.lpszClassName = windowName; 

    if (RegisterClassEx(&wc) == 0) return false;

    hwnd = CreateWindow(
        windowName,
        windowName,
        WS_OVERLAPPEDWINDOW,
        windowPosition.x, windowPosition.y,
        windowSize.x, windowSize.y,
        NULL,
        NULL,
        appHandle,
        NULL
        );
    if (!hwnd) return false;

    ShowWindow(hwnd, SW_SHOW);
    UpdateWindow(hwnd);

    return true;
}

WPARAM Window::Run()
{
    MSG msg = {0};
    while (PeekMessage(&msg, 0, 0, 0, PM_REMOVE))
    {
        TranslateMessage(&msg);
        DispatchMessage(&msg);
    }
    else
    {
        window.Render();
    }
    return msg.wParam;
}

bool WindowGL::SetPixels(HDC handleDC) const
{
    PIXELFORMATDESCRIPTOR pfd;
    ZeroMemory(&pfd, sizeof(pfd));
    pfd.nVersion = 1;
    pfd.dwFlags = PFD_SUPPORT_OPENGL | PFD_DRAW_TO_WINDOW | PFD_DOUBLEBUFFER;
    pfd.iPixelType = PFD_TYPE_RGBA;
    pfd.cColorBits = 32;
    pfd.cDepthBits = 32;
    pfd.iLayerType = PFD_MAIN_PLANE;
    int pixFormat = ChoosePixelFormat(handleDC, &pfd);
    if (pixFormat == 0) return false;
    if (!SetPixelFormat(handleDC, pixFormat, &pfd)) return false;

    return true;
}

bool WindowGL::InitWGL(HWND hwnd)
{
    handleDC= ::GetDC(hwnd);
    if (!SetPixels(handleDC)) return false;

    handleRC = wglCreateContext(handleDC);
    if (handleRC == NULL) return false;
    if (!wglMakeCurrent(handleDC, handleRC)) return false;
    return true;
}

void WindowGL::SetScene(bool isometricProjection)
{
    glViewport(0, 0, clientWidh, clientHeight);

    glMatrixMode(GL_PROJECTION);
    glLoadIdentity();

    float wsp = clientHeight / (float)clientWidh;
    if (!isometricProjection)
        glFrustum(-1.0f, 1.0f, wsp*-1.0f, wsp*1.0f, 1.0f, 10.0f);
    else
        glOrtho(-1.0f, 1.0f, wsp*-1.0f, wsp*1.0f, 1.0f, 10.0f);

    glMatrixMode(GL_MODELVIEW);
    glEnable(GL_DEPTH_TEST);
}

void WindowGL::DestroyWGL()
{
    wglMakeCurrent(NULL, NULL);
    wglDeleteContext(handleRC);
    ::ReleaseDC(hwnd, handleDC);
}

void WindowGL::Render()
{
    const float x0 = 1.0f;
    const float y0 = 1.0f;
    const float z0 = 1.0f;

    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
    glLoadIdentity();
    glTranslatef(0.0f, 0.0f, -3.0f);
    glColor4f(1.0f, 1.0f, 0.0f, 1.0f);

    glBegin(GL_TRIANGLES);
        glVertex3f(-x0, -y0,  0.0f); 
        glVertex3f( x0, -y0,  0.0f);
        glVertex3f(0.0f, y0,  0.0f);
    glEnd();

    SwapBuffers(handleDC); 
}

您无需知道文件的行数。

使用相同的'30eapril.txt'内容,输出为:

#!/usr/bin/env python3

class team: 
    def __init__(self, teamdata):
        self.name, self.wins, self.drawn, self.losses = teamdata
    def __repr__(self): 
        return self.name.ljust(15) + '{} {} {}'.format(self.wins, self.drawn, self.losses)

lag = []
with open('30eapril.txt', 'rt') as file:
    for line in file:
        lag.append(team(line.split()))

#print("Number of teams: " + str(len(lag)))
for l in lag:
    print(l)

'30eapril.txt'上的相同脚本有一个额外的行:

$ ./test_script3.py
Arsenal        2 1 0
Manchester     2 0 0
Liverpool      0 1 2
Newcastle      0 0 2
相关问题