用python写一个脚本查询txt文件中某几个单词出现的次数,并把结果输出生成一个新文件
#!bin/python
#-*- encoding: utf-8 -*-
def counter(path, find, punctuation):
infile = open(path, "r")
lenth = len(find)
count = []
for i in range(lenth):
count.append(0)
dat = infile.readline().strip("\n")
while dat != '':
dat = dat.split()
for elemt in dat:
elemt = elemt.strip(punctuation) #去除标点符号
if elemt in find:
i = find.index(elemt)
count[i] += 1
dat = infile.readline().strip("\n")
infile.close()
for i in range(lenth):
print "%s:%d次" % (find[i],count[i])
if __name__ == "__main__":
path = "PATH"
find = ["hello", "hi", "world"]
punctuation = ''',.;'":!?'''
counter(path, find, punctuation)
我是小白,看不太懂, infile = open(path, "r")这里的path是指查询的txt文件名么?还有就是输出生成新文件的代码是哪部分啊?
path就是查询的路径+文件名,
这个程序没有输出到文件,直接输出到了屏幕上,在倒数第五行上面。