Python计算一个文件里字数的方法

yipeiwu_com6年前Python基础

本文实例讲述了Python计算一个文件里字数的方法。分享给大家供大家参考。具体如下:

这段程序从所给文件中找出字数来。

from string import *
def countWords(s):
  words=split(s)
  return len(words)
  #returns the number of words
filename=open("welcome.txt",'r')
#open an file in reading mode
total_words=0
for line in filename:
  total_words=total_words + countWords(line)
  #counts the total words
print total_words

希望本文所述对大家的Python程序设计有所帮助。

相关文章

numpy给array增加维度np.newaxis的实例

如下所示: a[:, np.newaxis] # 给a最外层中括号中的每一个元素加[] a[np.newaxis, :] # 给a最外层中括号中所有元素加[] 以上这篇numpy给...

Python自然语言处理 NLTK 库用法入门教程【经典】

本文实例讲述了Python自然语言处理 NLTK 库用法。分享给大家供大家参考,具体如下: 在这篇文章中,我们将基于 Python 讨论自然语言处理(NLP)。本教程将会使用 Pyth...

tensorflow学习笔记之mnist的卷积神经网络实例

mnist的卷积神经网络例子和上一篇博文中的神经网络例子大部分是相同的。但是CNN层数要多一些,网络模型需要自己来构建。 程序比较复杂,我就分成几个部分来叙述。 首先,下载并加载数据:...

python try except 捕获所有异常的实例

如下所示: try: a=1 except Exception as e: print (e) import traceback import sys try: a = 1...

python logging模块的使用总结

日志级别 CRITICAL 50 ERROR 40 WARNING 30 INFO 20 DEBUG 10 logging.basicConfig()函数中的具...