在Python中计算文本的字数,可以通过以下几种方法:
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)
3. 使用`split`函数和字典来统计单词频率:
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中计算文本的字数。请选择适合你需求的方法进行操作
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。
如需转载请保留出处:https://sigusoft.com/bj/112463.html