新风花雪月 发表于 2017-5-8 12:21:47

统计文件件列表中包含单词的个数的 python 脚本

import sys;
import string;
def SearchWord(strFile, strWord):
print("Search file: ", strFile, " word:", strWord);
nCount = 0;
nLine = 0;
try:
hFile = open(strFile, "r");
try:
while True:
strLine = hFile.readline();               
if strLine:
#print(strLine);
nLineCount = FindStrCount(strLine, strWord);
nLine = nLine + 1;
print("line ", nLine, " count:", nLineCount);
nCount = nCount + nLineCount;
else:
break;
finally:
hFile.close();
except IOError:
print("open ", strFile , " failed!");
return nCount;   
def FindStrCount(strLine, strWord):
nFind = 0;
nIndex = 0;
while True:      
nIndex = strLine.find(strWord, nIndex);
if nIndex < 0:
break;
nFind = nFind + 1;
nIndex = nIndex + 1;
return nFind;   
if __name__ == "__main__":
#test for find sub string numbers
#str = "aa bb cc dd ee ee bb aa aa dd";
#print(FindStrCount(str, "bb"));
#test for count words
#print(SearchWord("c:\\c.txt", "=>"));
#sys.exit();
if 1 == len(sys.argv) or sys.argv in ("-h", "--help"):
print("usage: wc.py word file1 file2 ... filen");
sys.exit();
#count word
ls = [];
i = 0;
for i in range(0, len(sys.argv)):
if i > 1:
ls.append(sys.argv);
elif 1 == i:
strWord = sys.argv;
else:
print("work py file:", sys.argv);
print("search word:", strWord);
for strFile in ls:
print("parse file:", strFile);
print("find ", strWord, " count:", SearchWord(strFile, strWord));
页: [1]
查看完整版本: 统计文件件列表中包含单词的个数的 python 脚本