python - 在文本框 python 中以特定格式插入列表中的值

标签 python list collections tkinter counter

我目前正在使用 Python 2.7,以及 Tkinter 和集合。我的程序可以计算 .txt 文件中的单词数并将其保存到变量中。但是,当我 resultsBox.insert(END, document_data_Tally ) 时,它会显示为 Counter({'Test': 2, 'World': 1, 'Hello': 1})

我正在尝试将其转换为

的格式
Word : Value Word : Value
Word : Value Word : Value
Word : Value Word : Value

我希望它执行 10 行,然后从下一列开始。

import os
from Tkinter import *
from collections import Counter
import tkFileDialog

root = Tk()

root.title("Doc Word Frequency")
root.geometry("600x300")

def close_window (): 
    root.destroy()

def browse_directory():
    global filename
    filename = tkFileDialog.askopenfilename(parent=root,title='Choose a file')

    inputBox.delete(0, "end")
    inputBox.insert(0, filename)

def read_document():
    with open (os.path.basename(filename), "r") as myfile:
        document_data = myfile.read().replace('\n', '')

    document_data_list = re.sub("[^\w]", " ",  document_data).split()

    document_data_Tally = Counter(document_data_list)

    print(document_data_list)

    resultsBox.configure(state=NORMAL)
    resultsBox.insert(END, document_data_Tally )
    resultsBox.configure(state=DISABLED)

inputBox = Entry(root, width = 50)
inputBox.grid(row = 0, column = 0, padx = 20, pady = 20)
inputBox.insert(0, 'Upload Document')

Button(root, width = 9, text = 'Browse', command = browse_directory).grid(row = 0, column = 1, sticky = W, padx = 4)
Button(root, width = 9, text = 'Read', command = read_document).grid(row = 0, column = 2, sticky = W, padx = 4)
Button(root, width = 9, text = 'Quit', command = close_window).grid(row = 0, column = 3, sticky = W, padx = 4)

resultsBox = Text(root, width = 60, height = 10)
resultsBox.grid(columnspan = 4, padx = 10, pady = 10)
resultsBox.config(state=DISABLED)

mainloop( )
PS。我对 Python 还很陌生,任何建设性的批评都会受到赞赏。

最佳答案

您需要从计数器对象中提取数据,然后再将其放入文本中:

data = '\n'.join('{}\t{}'.format(k, v) for k, v in document_data_Tally.iteritems())

resultsBox.configure(state=NORMAL)
resultsBox.insert(END, data)
resultsBox.configure(state=DISABLED)

这将构建一个列表,该列表使用各自行上的制表符分隔单词及其计数,因此您应该在 resultsBox 中看到类似于下面的内容:

Test    2 
World   1 
Hello   1

关于python - 在文本框 python 中以特定格式插入列表中的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33048197/

相关文章:

Python-gphoto2 : how to capture image Canon 5D Mark IV

c# - 在列表中查找最接近一小时前的时间戳

java - Java 中泛型集合的多态性

java - 迭代器不工作

java - 我如何要求参数成为可变映射?

python - 从列数据框中清除某些数据

python - Pandas 和 GeoPandas 索引和切片

python - 获取特定 NCT ID 病史的临床试验

Python输入限制和重新提升

pandas - 根据条件从另一个数据框中复制列值