栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

python统计一个文本文件的字符数

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

python统计一个文本文件的字符数

# count lines, sentences, and words of a text file

# set all the counters to zero

lines, blanklines, sentences, words = 0, 0, 0, 0

print '-' * 50

try:

# use a text file you have, or google for this one ...

filename = 'GettysburgAddress.txt'

textf = open(filename, 'r')

except IOError:

print 'Cannot open file %s for reading' % filename

import sys

sys.exit(0)

# reads one line at a time

for line in textf:

print line, # test

lines += 1

if line.startswith('n'):

blanklines += 1

else:

# assume that each sentence ends with . or ! or ?

# so simply count these characters

sentences += line.count('.') + line.count('!') + line.count('?')

# create a list of words

# use None to split at any whitespace regardless of length

# so for instance double space counts as one space

tempwords = line.split(None)

print tempwords # test

# word total count

words += len(tempwords)

textf.close()

print '-' * 50

print "Lines : ", lines

print "Blank lines: ", blanklines

print "Sentences : ", sentences

print "Words : ", words

# optional console wait for keypress

from msvcrt import getch

getch()

开心洋葱 , 版权所有丨如未注明 , 均为原创丨未经授权请勿修改 , 转载请注明python统计文本文件内单词数量!

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/833849.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号