Python处理文本文件,统计单词出现次数

python代码时候,最好参照python Standard Library中文文档

【例1】读文本,并输出

python代码

f = file("number.txt")
while True:
    line = f.readline()
    if len(line) == 0:
         break
    print line
f.close()

效果如下:

【例2】读取多个文本文件,并统计文本中的单词个数

python代码

# coding=gb2312
import sys
import string

if len(sys.argv) == 1 or sys.argv[1] in {"-h", "--help"}:
    print("usage: uniqueword filename_1 filename_2 ... filename_n")
    sys.exit()
    #是否有输入参数,如果输入参数为空或者为-h, -help,则输出帮助信息
 
else:
    words = {}
    strip = string.whitespace + string.punctuation + string.digits + "\"'"
    #设置strip去掉文本中单词的空格,符号和数字
 
    for filename in sys.argv[1:]:
        for line in open(filename):
            for word in line.split():
                word = word.strip(strip)
                if len(word) >= 1:
                    words[word] = words.get(word, 0) + 1
    #逐一打开参数中指定的文件,并读取每一行,再用字符串的split方法把读取的行抽取出
    #每个单词,然后用strip过滤符号等,单词长度大于2的时候,把此单词加入到字典words中
    #其中words.get(word, 0)的意思是取出key等于word的value,如果key为空,则把value置为默认值0


for word in sorted(words):
    print("'{0}' occurs {1} times".format(word,words[word]))
    #排序打印

效果图:

转载需保留链接来源:VCBeta.CN » Python处理文本文件,统计单词出现次数

赞 (0)