1. 使用`len`函数和`rstrip`函数:
file_name = '白夜行.txt'try:with open(file_name, encoding='utf8') as file_obj:contents = file_obj.read()words = contents.rstrip()num_words = len(words)print(f'The file {file_name} has about {num_words} words.')except FileNotFoundError:print(f'Sorry, the file {file_name} does not exist.')
2. 使用`split`函数和`len`函数:
from string import splitdef countWords(s):words = split(s)return len(words)filename = 'welcome.txt'total_words = 0with open(filename, 'r') as file:for line in file:total_words += countWords(line)print(total_words)

import stringdef count_words(s, n):s = s.lower()s = s.replace(string.punctuation, ' ')words = s.split()counts = {}for w in words:counts[w] = counts.get(w, 0) + 1items = sorted(counts.items(), key=lambda x: (-x, x))return items[:n]print(count_words('betty bought a bit of butter but the butter was bitter', 3))
4. 使用`tkinter`库和定时器来实时显示文本字数:
import tkinter as tkdef getlen():txt = tk_text.get(1.0, tk.END)txt_len = len(txt) - 1 Subtract 1 to exclude the newline characterprint(f'{txt_len}')tk_main.after(10000, getlen) Update every 10 secondstk_main = tk.Tk()tk_text = tk.Text(tk_main)tk_text.pack()getlen()tk_main.mainloop()
以上方法可以帮助你在Python中计算文本的字数。请选择适合你需求的方法进行操作
