-
Notifications
You must be signed in to change notification settings - Fork 25
/
wordcount1.py
executable file
·122 lines (89 loc) · 3.24 KB
/
wordcount1.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
#!/usr/bin/env python3
# Copyright © 2012-13 Qtrac Ltd. All rights reserved.
# This program or module is free software: you can redistribute it and/or
# modify it under the terms of the GNU General Public License as published
# by the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version. It is provided for educational
# purposes and is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# General Public License for more details.
import html.parser
import os
import re
import sys
def main():
if len(sys.argv) == 1 or sys.argv[1] in {"-h", "--help"}:
print("usage: {} <files>".format(os.path.basename(sys.argv[0])))
sys.exit(1)
count_words_in_files(sys.argv[1:])
def count_words_in_files(files):
total = 0
for filename in files:
count = count_words(filename)
if count is not None:
total += count
print("{:9,} words in {}".format(count, filename))
print("total: {:,} words".format(total))
def count_words(filename):
for wordCounter in (PlainTextWordCounter, HtmlWordCounter):
if wordCounter.can_count(filename):
return wordCounter.count(filename)
class AbstractWordCounter:
@staticmethod
def can_count(filename):
raise NotImplementedError()
@staticmethod
def count(filename):
raise NotImplementedError()
class PlainTextWordCounter(AbstractWordCounter):
@staticmethod
def can_count(filename):
return filename.lower().endswith(".txt")
@staticmethod
def count(filename):
if not PlainTextWordCounter.can_count(filename):
return 0
regex = re.compile(r"\w+")
total = 0
with open(filename, encoding="utf-8") as file:
for line in file:
for _ in regex.finditer(line):
total += 1
return total
class HtmlWordCounter(AbstractWordCounter):
class __HtmlParser(html.parser.HTMLParser):
def __init__(self):
super().__init__()
self.regex = re.compile(r"\w+")
self.inText = True
self.text = []
self.count = 0
def handle_starttag(self, tag, attrs):
if tag in {"script", "style"}:
self.inText = False
def handle_endtag(self, tag):
if tag in {"script", "style"}:
self.inText = True
else:
for _ in self.regex.finditer(" ".join(self.text)):
self.count += 1
self.text = []
def handle_data(self, text):
if self.inText:
text = text.rstrip()
if text:
self.text.append(text)
@staticmethod
def can_count(filename):
return filename.lower().endswith((".htm", ".html"))
@staticmethod
def count(filename):
if not HtmlWordCounter.can_count(filename):
return 0
parser = HtmlWordCounter.__HtmlParser()
with open(filename, encoding="utf-8") as file:
parser.feed(file.read())
return parser.count
if __name__ == "__main__":
main()