gpt4 book ai didi

python - 从桌面文本文件创建一列并在 python tkinter 中将其识别为正面、负面或中性句子

转载 作者:太空狗 更新时间:2023-10-30 02:16:21 26 4
gpt4 key购买 nike

我想在 python gui 中创建一个 (nx2) 表,其中 n 是我在文本文件中的句子数量,我的第二列将包含一个滚动条,我可以在其中手动分配(正或负或中性)值到它。目前,我可以使用以下代码从文本文件中获取句子:-

root=Tk()

def openInstruktion():
from subprocess import call
call("notepad c:\\Users\\Desktop\\tweets.txt")

instruktionBtn = Button(root, text='tweets', command=openInstruktion)
instruktionBtn.grid(row=6, column=0)
root.mainloop()

Gui 应该是这样的:- Image

提前感谢您的帮助。

最佳答案

Screenshot

首先,要从您的文本文件中读取推文,请尝试使用 .readlines() :

# Get the list of tweets from a text file
with open("c:\\Users\\summert\\Desktop\\tweets.txt") as f:
tweets = [x.strip() for x in f.readlines()]

然后,创建“表格”的一种简单方法是使用 grid 对齐小部件方法。

最后,你可以添加一个scrollbar如果表格太长:

import tkinter as tk
from tkinter import ttk

root = tk.Tk()
label_tweet = tk.Label(root, text="Tweet", width=28)
label_tweet.grid(row=0, column=0, padx=(20,0), pady=5)
label_sentiment = tk.Label(root, text="Sentiment", width=15)
label_sentiment.grid(row=0, column=1, padx=(0,30), pady=5)

# Create a table container with a scrollbar using a canvas
table_container = tk.Frame(root)
table_container.grid(row=1, column=0, columnspan=2, padx=20)
canvas = tk.Canvas(table_container, highlightthickness=0)
frame = tk.Frame(canvas)
vsb = ttk.Scrollbar(table_container, orient="vertical", command=canvas.yview)
canvas.configure(yscrollcommand=vsb.set)
canvas.pack(side="left", fill="both", expand=True)
vsb.pack(side="left", fill="y")
canvas.create_window((0,0), window=frame, anchor="nw")

# Put the tweets in a hand-made "table"
possibleSentiments = ["Positive", "Neutral", "Negative"]
sentimentBoxes = []
for i, tweet in enumerate(tweets):
# Create an entry box for the tweet
e = ttk.Entry(frame, width=35)
e.insert(0, tweet)
e.grid(row=i+1, column=0)
# Create a combobox for the associated sentiment
c = ttk.Combobox(frame, values=possibleSentiments, width=12, state="readonly")
c.set(possibleSentiments[1])
c.grid(row=i+1, column=1)
sentimentBoxes.append(c)

# Add a button to save the tweets and sentiments in a CSV file
def saveSentiments():
sentiments = [c.get() for c in sentimentBoxes]
print(sentiments)
with open('tweetSentiments.csv', 'w') as csvfile:
for i in range(len(tweets)):
csvfile.write('"{}","{}"\n'.format(tweets[i], sentiments[i]))

button = tk.Button(root, text="Save sentiments", command=saveSentiments)
button.grid(row=2, column=0, columnspan=2, pady=10)

# Resize the canvas
root.update()
frame_width = frame.winfo_width()
canvas.config(width=frame_width, height=140)
canvas.configure(scrollregion=canvas.bbox("all"))

# Launch the app
root.mainloop()

关于python - 从桌面文本文件创建一列并在 python tkinter 中将其识别为正面、负面或中性句子,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44493363/

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