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之将矩阵拉成向量的实例

废话不多说,直接上代码吧! # 矩阵操作 # 将矩阵拉成向量 import numpy as np x = np.arange(10).reshape(2,5) print(x)...

Python删除n行后的其他行方法

如下所示: #!/usr/bin/python #-*- coding: utf-8 -*- fin=open('add_1.txt') a=fin.readlines() #...

python双向链表实现实例代码

python双向链表实现实例代码

示意图:python双向链表实现代码:#!/usr/bin/python # -*- coding: utf-8 -*- class&nbs...

运用PyTorch动手搭建一个共享单车预测器

运用PyTorch动手搭建一个共享单车预测器

本文摘自 《深度学习原理与PyTorch实战》 我们将从预测某地的共享单车数量这个实际问题出发,带领读者走进神经网络的殿堂,运用PyTorch动手搭建一个共享单车预测器,在实战过程中掌握...

Python中list列表的一些进阶使用方法介绍

判断一个 list 是否为空 传统的方式: if len(mylist): # Do something with my list else: # The list is e...