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程序设计有所帮助。

相关文章

Python中用psycopg2模块操作PostgreSQL方法

Python中用psycopg2模块操作PostgreSQL方法

其实在Python中可以用来连接PostgreSQL的模块很多,这里比较推荐psycopg2。psycopg2安装起来非常的简单(pip install psycopg2),这里主要重点...

python 图像平移和旋转的实例

如下所示: import cv2 import math import numpy as np def move(img): height, width, channels = i...

Python3.5运算符操作实例详解

Python3.5运算符操作实例详解

本文实例讲述了Python3.5运算符操作。分享给大家供大家参考,具体如下: 1、运算符的分类 2、算术运算符 示例代码: #!/usr/bin/env python #...

python实现飞机大战微信小游戏

python实现飞机大战微信小游戏

0、前言 我学一种语言,可以说学任何东西都喜欢自己动手实践,总感觉自己动手一遍,就可以理解的更透彻,学python也一样,自己动手写代码,但更喜欢做点小东西出来,一边玩一边学。下面我就展...

Python正则捕获操作示例

本文实例讲述了Python正则捕获操作。分享给大家供大家参考,具体如下: 目的: 给表达式 '10+6/5-4*2' 中每个运算符左右都加一个空格字符,变成:'10 + 6 / 5 -...