【Python新手参考】带界面的英文单词计数器

事情经过

昨天晚上用电脑写作文,由于不放心Word的计词器,一时又找不到合适的工具,于是索性自己写了一个。那么为什么要带界面呢?原因是我曾经尝试过input(),但是它不能处理文本中的换行,所以只能将tkinter.Text作为输入框。

写完之后我发现这个东西似乎还有点参考价值,故post出来。

包含功能

  • 单词、字符、句子、段落计数器
  • 自动更新统计信息
  • 界面和多行输入
  • 快速清空、粘贴

源码

作为一个送给新手的参考代码,这东西必须开源,我打算让它遵循DWTFYWWI开原许可,即“Do Whatever The Fxxk You Want With It”。

GitHub仓库:https://github.com/TotoWang-hhh/en_word_count/

什么?你不想去神奇的GitHub?


import tkinter as tk
import tkinter.ttk as ttk
import threading
import pyclip


def _count(word):
lines=word.split('\n')
while '' in lines:
lines.remove('')
words=[]
for line in lines:
lineword=line.split(' ')
for lw in lineword:
words.append(lw)
while '' in words:
words.remove('')
sentencecount=0
charindex=0
notriperiod=word.replace('...','') #Ignore ellipsis
for char in notriperiod:
if char=='.':
sentencecount+=1
charindex+=1
#words.remove(' ')
#words.remove('\n')
return len(words),sentencecount,len(lines)


def count():
wordcount,sentencecount,paracount=_count(txtinput.get(1.0,tk.END))
countlabel['text']=str(wordcount)+' Words'+' | '+str(len(txtinput.get(1.0,tk.END))-1)+' Chars'+\
' | '+str(sentencecount)+' Sentences (Periods)'+' | '+str(paracount)+' Paras (Lines)'


def updatecount():
end=False
while win.winfo_exists() and not end:
try:
count()
except:
print('EXIT')
end=True
break
print('EXIT')
exit()


def paste():
txtinput.insert(tk.INSERT,pyclip.paste(encoding='utf-8'))


win=tk.Tk()
win.title('English Word Count')
win.minsize(640,360)
win.geometry('640x360')


txtinput=tk.Text(win,bd=0)


tk.Label(win,text='2023 By rgzz666').pack(side=tk.BOTTOM,fill=tk.X)


countrow=tk.Frame(win)


ttk.Button(countrow,text='REFRESH',command=count).pack(side=tk.RIGHT)
ttk.Button(countrow,text='↑ PASTE',command=paste).pack(side=tk.RIGHT)
ttk.Button(countrow,text='X CLEAR',command=lambda:txtinput.delete(1.0,tk.END)).pack(side=tk.RIGHT)


countlabel=tk.Label(countrow,text='Please press REFRESH first',anchor='w')
countlabel.pack(fill=tk.X)


countrow.pack(side=tk.BOTTOM,fill=tk.X)


txtinput.pack(fill=tk.BOTH,expand=True)


update_t=threading.Thread(target=updatecount)
update_t.start()


win.mainloop()

 

瞎几把讲解

_count()

传入文本,返回单词、句子、段落计数

count()

获取输入框内容,调用_count()计数,然后修改统计信息

updatecount()

循环调用count(),自动更新统计信息

paste()

通过pyclip粘贴剪贴板内容到输入框

界面部分

想学的自己先去看tkinter教程,懒得讲

什么?你怎么知道我又在这里藏了东西

posted @ 2023-09-11 18:24  真_人工智障  阅读(82)  评论(1编辑  收藏  举报