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

发布时间 2023-09-11 18:26:40作者: 真_人工智障

事情经过

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

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

包含功能

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

源码

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

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

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

 1 import tkinter as tk
 2 import tkinter.ttk as ttk
 3 import threading
 4 import pyclip
 5 
 6 def _count(word):
 7     lines=word.split('\n')
 8     while '' in lines:
 9         lines.remove('')
10     words=[]
11     for line in lines:
12         lineword=line.split(' ')
13         for lw in lineword:
14             words.append(lw)
15     while '' in words:
16         words.remove('')
17     sentencecount=0
18     charindex=0
19     notriperiod=word.replace('...','') #Ignore ellipsis
20     for char in notriperiod:
21         if char=='.':
22             sentencecount+=1
23         charindex+=1
24     #words.remove(' ')
25     #words.remove('\n')
26     return len(words),sentencecount,len(lines)
27 
28 def count():
29     wordcount,sentencecount,paracount=_count(txtinput.get(1.0,tk.END))
30     countlabel['text']=str(wordcount)+' Words'+' | '+str(len(txtinput.get(1.0,tk.END))-1)+' Chars'+\
31                        ' | '+str(sentencecount)+' Sentences (Periods)'+' | '+str(paracount)+' Paras (Lines)'
32 
33 def updatecount():
34     end=False
35     while win.winfo_exists() and not end:
36         try:
37             count()
38         except:
39             print('EXIT')
40             end=True
41             break
42     print('EXIT')
43     exit()
44 
45 def paste():
46     txtinput.insert(tk.INSERT,pyclip.paste(encoding='utf-8'))
47 
48 win=tk.Tk()
49 win.title('English Word Count')
50 win.minsize(640,360)
51 win.geometry('640x360')
52 
53 txtinput=tk.Text(win,bd=0)
54 
55 tk.Label(win,text='2023 By rgzz666').pack(side=tk.BOTTOM,fill=tk.X)
56 
57 countrow=tk.Frame(win)
58 
59 ttk.Button(countrow,text='REFRESH',command=count).pack(side=tk.RIGHT)
60 ttk.Button(countrow,text='↑ PASTE',command=paste).pack(side=tk.RIGHT)
61 ttk.Button(countrow,text='X CLEAR',command=lambda:txtinput.delete(1.0,tk.END)).pack(side=tk.RIGHT)
62 
63 countlabel=tk.Label(countrow,text='Please press REFRESH first',anchor='w')
64 countlabel.pack(fill=tk.X)
65 
66 countrow.pack(side=tk.BOTTOM,fill=tk.X)
67 
68 txtinput.pack(fill=tk.BOTH,expand=True)
69 
70 update_t=threading.Thread(target=updatecount)
71 update_t.start()
72 
73 win.mainloop()

瞎几把讲解

_count()

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

count()

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

updatecount()

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

paste()

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

界面部分

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

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