在pygame应用程序中显示文本文件中的单词

时间:2014-01-02 15:46:50

标签: python pygame words

我目前仍然坚持能够获取10个最高频率的单词,并能够在我的pygame应用程序中显示它们。

The text file called nounTree.txt:
people,372
history,100
way,185
art,60
money,174
world,51
information,50
map,67
two,69
family,210
government,190
health,45
system,11
computer,19
meat,75
year,96
thanks,32
music,80
person,80
reading,77

基本上我想要做的是按频率(我已经完成)订购一个txt文件,现在取前10个单词(得分最高的单词)。然后我想在我的pygame应用程序中使用那些前10个单词在窗格中显示它们。窗格1中的频率最高的单词,窗格10中的最低频率单词(请参阅下面的图片,我的意思是): enter image description here 因此,基本上在订购时,您会将人们放入矩形1中。<​​/ p>

这是我订购文本文件的代码(BoxAlgorithm.py):

import fileinput #I think I might need it
import displayBox


def fileSort():
    with open("nounTree.txt") as file:
        nouns = []
        for line in file:
            noun, count = line.split(",")
            nouns.append((int(count), noun))

    nouns.sort()

    for count, noun in nouns:
        list1 = print("{0},{1}".format(noun,count))


displayBox.Application()

这是displayBox.py代码:

import pygame
import sys


WHITE = (255,255,255)
BLACK = (0  ,0  ,0  )



MAIN_BUTTON = 2

KEYBOARD = True
WORDS = False



class Pane():

    def __init__(self, textToDisplay, textValue, coordinates, screen):

        self.textToDisplay = textToDisplay
        self.textValue = textValue
        self.coordinates = coordinates
        self.screen = screen
        self.font = pygame.font.SysFont('Palace Script MT', 25)



    def coordinates(self):
        return self.coordinates



    def text(self):
        return self.textValue



    def drawPane(self):
        pygame.draw.rect(self.screen, BLACK, self.coordinates, 2)
        self.screen.blit(self.font.render(self.textToDisplay, True, BLACK), self.coordinates)



class Terminal(Pane):

    def __init__(self, textToDisplay, coordinates, screen):

        Pane.__init__(self, textToDisplay, "", coordinates, screen)

        self.text = "" # keeps text displayed in top pane
        self.text_pos = (10,20) # left margin, top margin
        self.text_changed = True
        self.cursor_visible = True # changes after self.cursor_delay
        self.cursor_delay = 500 # This is 0.5 second
        self.cursor_next_change = pygame.time.get_ticks() + self.cursor_delay

    def draw(self):
        self.drawPane() 
        self.drawText()

    def drawText(self):
        #TODO: split self.text to lines

        # changes the cursor visibility
        if self.cursor_next_change <= pygame.time.get_ticks():
            self.cursor_next_change = pygame.time.get_ticks() + self.cursor_delay
            self.cursor_visible = not self.cursor_visible
            self.text_changed = True

        # renders new text only if text was changed (or cursor changed visibility)
        if self.text_changed:
            if self.cursor_visible:
                self.text_surface = self.font.render(self.text+"_", True, BLACK)
            else:
                self.text_surface = self.font.render(self.text, True, BLACK)

            self.text_rect = self.text_surface.get_rect(topleft = self.text_pos)
            self.text_changed = False

        self.screen.blit(self.text_surface, self.text_rect)

    def setText(self, text):
        self.text = text
        self.text_changed = True

    def addText(self, text):
        if text == "Backspace":
            if self.text: # text not empty
                self.text = self.text[:-1] # delete last char
        else:
            self.text += text
        self.text_changed = True

    def addWord(self, text):
        if text == "Backspace":
            if self.text: # text not empty
                self.text = self.text[:-1] # delete last char
        else:
            if self.text:
                self.text += " " # adds space before word
            self.text += text
        self.text_changed = True


class Application():

    NoOfPanes = 0
    NoOfKeys = 0
    Panes = []
    Keys = []

    paneLocs = [(583, 334, 300, 150), 
                            (633, 150, 200, 125), 
                            (633, 600, 200, 125), 
                            (350, 360, 200, 100), 
                            (925, 360, 200, 100), 
                            (1000, 150, 150, 100), 
                            (275, 150, 150, 100), 
                            (275, 600, 150, 100), 
                            (1000, 600, 150, 100), 
                            (75, 350, 200, 100),
                            (0, 668, 200, 100)
                            ]    

    keyboardPaneLocs = [(0, 100, 50, 50),
                        (75, 100, 50, 50),
                        (150, 100, 50, 50),
                        (225, 100, 50, 50),
                        (300, 100, 50, 50),
                        (375, 100, 50, 50),
                        (450, 100, 50, 50),
                        (525, 100, 50, 50),
                        (600, 100, 50, 50),
                        (675, 100, 50, 50),
                        (0, 200, 50, 50),
                        (75, 200, 50, 50),
                        (150, 200, 50, 50),
                        (225, 200, 50, 50),
                        (300, 200, 50, 50),
                        (375, 200, 50, 50),
                        (450, 200, 50, 50),
                        (525, 200, 50, 50),
                        (600, 200, 50, 50),
                        (675, 200, 50, 50),
                        (0, 300, 50, 50),
                        (75, 300, 50, 50),
                        (150, 300, 50, 50),
                        (225, 300, 50, 50),
                        (300, 300, 50, 50),
                        (375, 300, 50, 50),
                        (450, 300, 50, 50),
                        (525, 300, 50, 50),
                        (600, 300, 50, 50),
                        (0, 400, 50, 50),
                        (75, 400, 50, 50),
                        (150, 400, 50, 50),
                        (225, 400, 50, 50),
                        (300, 400, 50, 50),
                        (375, 400, 50, 50),
                        (450, 400, 50, 50),
                        (525, 400, 125, 50),
                        (0, 668, 200, 100),
                        (800, 150, 100, 50)]

    textPaneLoc = [(0, 0, 1000, 100)]



    def __init__(self):

        pygame.init()
        pygame.display.set_caption('Box Test')

        self.font = pygame.font.SysFont('Arial', 25)
        self.screen = pygame.display.set_mode((1366,768), 0, 32)

        self.show_panes = True
        self.show_keyboard = False
        self.show_terminal = True

        self.createPanes()
        self.createKeyboard()

        self.terminal = Terminal("", (0,0, 1000, 100), self.screen)

    def close(self):
        print ("pygame quit")
        pygame.quit()
        sys.exit()



    def createPanes(self):
        self.addPane("1", WORDS)
        self.addPane("2", WORDS)
        self.addPane("3", WORDS)
        self.addPane("4", WORDS)
        self.addPane("5", WORDS)
        self.addPane("6", WORDS)
        self.addPane("7", WORDS)
        self.addPane("8", WORDS)
        self.addPane("9", WORDS)
        self.addPane("10", WORDS)
        self.addPane("Keyboard", WORDS)



    def createKeyboard(self):
        self.addPane("1", KEYBOARD)
        self.addPane("2", KEYBOARD)
        self.addPane("3", KEYBOARD)
        self.addPane("4", KEYBOARD)
        self.addPane("5", KEYBOARD)
        self.addPane("6", KEYBOARD)
        self.addPane("7", KEYBOARD)
        self.addPane("8", KEYBOARD)
        self.addPane("9", KEYBOARD)
        self.addPane("0", KEYBOARD)
        self.addPane("Q", KEYBOARD)
        self.addPane("W", KEYBOARD)
        self.addPane("E", KEYBOARD)
        self.addPane("R", KEYBOARD)
        self.addPane("T", KEYBOARD)
        self.addPane("Y", KEYBOARD)
        self.addPane("U", KEYBOARD)
        self.addPane("I", KEYBOARD)
        self.addPane("O", KEYBOARD)
        self.addPane("P", KEYBOARD)
        self.addPane("A", KEYBOARD)
        self.addPane("S", KEYBOARD)
        self.addPane("D", KEYBOARD)
        self.addPane("F", KEYBOARD)
        self.addPane("G", KEYBOARD)
        self.addPane("H", KEYBOARD)
        self.addPane("J", KEYBOARD)
        self.addPane("K", KEYBOARD)
        self.addPane("L", KEYBOARD)
        self.addPane("Z", KEYBOARD)
        self.addPane("X", KEYBOARD)
        self.addPane("C", KEYBOARD)
        self.addPane("V", KEYBOARD)
        self.addPane("B", KEYBOARD)
        self.addPane("N", KEYBOARD)
        self.addPane("M", KEYBOARD)
        self.addPane(" ", KEYBOARD)
        self.addPane("Boxes", KEYBOARD)
        self.addPane("Backspace", KEYBOARD)



    def addPane(self, textToDisplay, keyboardFlag):      
        if (not keyboardFlag) and (self.NoOfPanes > 11):
            print("Limit Reached")            
        else:
            print(int(self.NoOfPanes))

            if keyboardFlag:
                self.Keys.append(Pane(textToDisplay, textToDisplay, self.keyboardPaneLocs[self.NoOfKeys], self.screen))
                self.NoOfKeys += 1
            else:
                self.Panes.append(Pane(textToDisplay, textToDisplay, self.paneLocs[self.NoOfPanes], self.screen))
                self.NoOfPanes += 1


    def drawPanes(self):
        for Pane in self.Panes:
            Pane.drawPane()



    def drawKeyboard(self):
        for Key in self.Keys:
            Key.drawPane()



    def mousePosition(self, event):
        if event.type == MAIN_BUTTON:
            self.Pos = pygame.mouse.get_pos()
            return MAIN_BUTTON
        else:
            return False



    def mouseDown(self):
        posx,posy = pygame.mouse.get_pos()      
        textToReturn = "Nothing selected"
        if self.show_panes:
            for Pane in self.Panes:
                paneCoords = Pane.coordinates
                print(str(paneCoords[0]) + ":" + str(paneCoords[1]) + ":" + str(paneCoords[2]) + ":" + str(paneCoords[3]))
                if (paneCoords[0] <= posx <= paneCoords[0]+paneCoords[2]) and (paneCoords[1] <= posy <= paneCoords[1]+paneCoords[3]):
                    textToReturn = Pane.text()
        elif self.show_keyboard:
            for Pane in self.Keys:
                paneCoords = Pane.coordinates
                print(str(paneCoords[0]) + ":" + str(paneCoords[1]) + ":" + str(paneCoords[2]) + ":" + str(paneCoords[3]))
                if (paneCoords[0] <= posx <= paneCoords[0]+paneCoords[2]) and (paneCoords[1] <= posy <= paneCoords[1]+paneCoords[3]):            
                    textToReturn = Pane.text()

        return textToReturn



    def run(self):

        clock = pygame.time.Clock()

        RUNNING = True
        while RUNNING:

            for event in pygame.event.get():

                if event.type == pygame.QUIT:
                    RUNNING = False
                    break

                if event.type == pygame.KEYDOWN:
                    if event.key == pygame.K_ESCAPE:
                        self.show_keyboard = not self.show_keyboard
                        self.show_panes = not self.show_panes

                if event.type == pygame.MOUSEBUTTONUP:
                    textSelected = self.mouseDown()
                    print(textSelected)
                    if textSelected == "Keyboard":

                        self.show_keyboard = True
                        self.show_panes = False
                    elif textSelected == "Boxes":
                        self.show_keyboard = False
                        self.show_panes = True
                    elif textSelected != "Nothing selected":
                        if self.show_keyboard:
                            self.terminal.addText(textSelected)
                        else:
                            self.terminal.addWord(textSelected)

            # --- draws ---

            self.screen.fill(WHITE)

            if self.show_panes:
                self.drawPanes()

            if self.show_keyboard:
                self.screen.blit(self.font.render("Spacebar", True, BLACK), (525, 400, 100, 50))
                self.drawKeyboard()

            if self.show_terminal:
                self.terminal.draw()

            pygame.display.update()

            # --- FPS ---

            clock.tick(60)

        self.close()    


Application().run()

非常感谢任何帮助。也是新年快乐的家伙/女孩。

1 个答案:

答案 0 :(得分:2)

关于你问题的PyGame部分,我无法帮助你,但你应该使用csv module来阅读你的数据。

import csv
from pprint import pprint

with open("nounTree.txt") as in_file:
    reader = csv.reader(in_file)
    data = [[row[0], int(row[1])] for row in list(reader)]

top10 = sorted(data, key=lambda x: -x[1])[:10]
pprint(top10)

这会产生

[['people', 372],
 ['family', 210],
 ['government', 190],
 ['way', 185],
 ['money', 174],
 ['history', 100],
 ['year', 96],
 ['music', 80],
 ['person', 80],
 ['reading', 77]]

我不太确定你打算如何在Python中这样做,但是你试过把我上面编写的代码放在一个函数中,然后从createPanes()调用它吗?如果我们改变上面的代码:

# Remember to import csv somewhere in your code
def get_n_nouns(n):
    """
    Returns the n most common nouns
    """
    with open("nounTree.txt") as in_file:
        reader = csv.reader(in_file)
        data = [[row[0], int(row[1])] for row in list(reader)]

    return sorted(data, key=lambda x: -x[1])[:n]

您可以插入这些值in createPanes()

def createPanes():
    words = get_n_nouns(10)
    for word, count in words:
        self.addPane("{}: {}".format(word, count), WORDS)

如果我正确理解PyGame代码,那么应在{1}窗格中添加people: 372。请记住我对PyGame的有限经验:)

相关问题