且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Python之每日一练统计英文文本单词出现的个数、行数、字符数

更新时间:2022-01-18 08:32:03

第四题:任一个英文的纯文本文件,统计其中的单词出现的个数。

一、首先获取纯英文的文本,这里以获取“Python之禅”为例,见代码如下

# -*- coding: utf-8 -*-

import sys

origin = sys.stdout#标准输出

f =open('file.txt', 'w')

sys.stdout = f

# ===================================

print 'Start of program'

# 你的程序放到这里,过程中所有print到屏幕的内容都同时保存在file.txt里面了。

import this

print 'End of program'

# ===================================

sys.stdout = origin

f.close()

Python之每日一练统计英文文本单词出现的个数、行数、字符数
运行结果

二、输出纯英文文本单词个数

#coding:utf-8

import sys,os

"""

python实现任一个英文的纯文本文件,统计其中的单词出现的个数、行数、字符数

"""

file_name ="file.txt"

line_counts =0    #行数

word_counts =0  #个数

character_counts =0  #字符数

with open(file_name, 'r')as f:

for linein f:

words = line.split()#split()用于分割,分隔符可以自己制定

        line_counts +=1

        word_counts +=len(words)

character_counts +=len(line)

print "line_counts ", line_counts

print "word_counts ", word_counts

print "character_counts ", character_counts

Python之每日一练统计英文文本单词出现的个数、行数、字符数
运行结果