Я не могу отобразить количество букв на графике в Python - PullRequest
0 голосов
/ 12 февраля 2020

У меня есть рабочий текстовый редактор на Python с GUI, который анализирует текстовый файл и показывает количество слов и букв. Теперь я пытаюсь отобразить график (используя matplotlib), чтобы показать график распределения, который в основном показывает частоту каждого слова (за исключением пробелов). Вот код:

import string
import tkinter as tk
from tkinter import Tk, scrolledtext, Menu, filedialog, END, messagebox, simpledialog
import tkinter.scrolledtext as ScrolledText
from tkinter import *
import matplotlib
import matplotlib.pyplot as plt
matplotlib.use("TkAgg")

import numpy as np
from matplotlib import colors
from matplotlib.ticker import PercentFormatter

import pandas as pd
import seaborn as sns
from scipy import stats

from collections import Counter



root = Tk (className = " Text Editor")
textArea = ScrolledText.ScrolledText(root, width = 100, height = 50)
textArea.pack()


def newFile():
    if len(textArea.get('1.0', END+'-1c')) > 0:
        if messagebox.askyesno("Save", "Would you like to save?"):
            saveFile()
        else:
            textArea.delete('1.0', END)
    root.title("TEXT EDITOR")
def OpenFile():
    file = filedialog.askopenfile(parent = root, title = 'Select a text file', filetypes = (("Text file", ".txt"),("All files", "*.*")))
    if file != None:
        contents = file.read()
        textArea.insert('1.0', contents)
        file.close()

def saveFile():
    file = filedialog.asksaveasfile(mode='w')
    if file!= None:
        data = textArea.get('1.0', END+'-1c')
        file.write(data)
        file.close()
def exit():
    if messagebox.askyesno("Quit", "Are you sure you want to quit?"):
        root.destroy()

Вот функция, отвечающая за создание сюжета. Я использовал словарь для хранения данных. В настоящее время он работает, но я не знаю, почему он показывает одинаковое количество каждой буквы.

def PlotButton():
    text = open("dest.txt", "r")
    d = dict()

    for line in text:
        line = line.strip()
        line = line.lower()
        line = line.translate(line.maketrans("", "", string.punctuation))
        words = line.split(" ")
        for word in words:
            for i in word:
                if i in d:
                    d[i] = d[i] + 1
                else:
                    d[i] = 1
[This is the output for the plot creating button][1]
    c = Counter(('\n'.join(key for key, val in d.items())))
    plt.bar(*zip(*c.most_common()), width=.5, color='g')
    plt.show()

.

def about():
    label = messagebox.showinfo("About", "A simple text editor 0.2")
def AnalyzeLetters():
    text = open("dest.txt", "r")
    d = dict()

    for line in text:
        line = line.strip()
        line = line.lower()
        line = line.translate(line.maketrans("", "", string.punctuation))
        words = line.split(" ")
        for word in words:
            for i in word:
                if i in d:
                    d[i] = d[i] + 1
                else:
                    d[i] = 1
    # messagebox.showinfo('Analyze Data', '\n'.join(key+':'+str(val) for key, val in d.items()))

    win = tk.Toplevel(root)
    win.geometry('+%s+%s' % (root.winfo_x() + 100, root.winfo_y() + 50))
    win.transient(root)
    result = tk.Text(win, width=40, height=20)
    result.pack()
    for key in sorted(d.keys()):
        result.insert('end', '%s: %s\n' % (key, d[key]))
    win.grab_set()


def countWords():
    text = open("dest.txt", "r")
    d = dict()
    for line in text:
        line = line.strip()

        line = line.lower()

        words = line.split(" ")

        for word in words:
            if word in d:
                d[word] = d[word] + 1
            else:
                d[word] = 1
    # messagebox.showinfo('Analyze Data', '\n'.join(key+':'+str(val) for key, val in d.items()))
    win = tk.Toplevel(root)
    win.geometry('+%s+%s' % (root.winfo_x() + 100, root.winfo_y() + 50))
    win.transient(root)
    result = tk.Text(win, width=40, height=20)
    result.pack()
    for key in sorted(d.keys()):
        result.insert('end', '%s: %s\n' % (key, d[key]))
    win.grab_set()


def create_window():
    root = tk.Tk()
    root.title("Analized data")
    text1 = tk.Text(root, height=10, width=50)

    text1.config(state="normal")
    text1.insert(tk.INSERT,"Check")
    text1.pack()
    root.mainloop()

menu = Menu(root)
root.config(menu=menu)
FMenu = Menu(menu)
menu.add_cascade(label = "File", menu = FMenu)
FMenu.add_command(label = "New", command = newFile)
FMenu.add_command(label = "Open", command = OpenFile)
FMenu.add_command(label = "Save", command = saveFile)
FMenu.add_separator()
FMenu.add_command(label = "Exit", command = exit)

helpMenu = Menu(menu)
menu.add_cascade(label = "Count leters", command = AnalyzeLetters)
menu.add_cascade(label = "Count words", command = countWords)
menu.add_cascade(label = "Create plot", command = PlotButton)
menu.add_cascade(label = "About", command = about)

textArea.pack()
root.mainloop()
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...