gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 05:28:23 25 4
gpt4 key购买 nike

我目前坚持能够获取 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 个单词(得分最高的单词)。然后,我想使用这些前 10 个单词将它们显示在我的 pygame 应用程序的 Pane 中。频率最高的单词在 Pane 1 中,频率最低的单词在 Pane 10 中(请看下图了解我的意思): enter image description here所以基本上当它被订购时,你会带人把它放在矩形 1 中。

这是我用于订购文本文件的代码(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()

非常感谢您提供的任何帮助。也祝各位新年快乐。

最佳答案

关于你问题的 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 代码,这应该添加 people: 372在 Pane #1 等中。请记住我对 PyGame 的有限经验:)

关于python - 在pygame应用程序中显示文本文件中的单词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20886479/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com