Skip to content

Commit c4e42d1

Browse files
committed
wc command
1 parent a496168 commit c4e42d1

1 file changed

Lines changed: 64 additions & 0 deletions

File tree

  • implement-shell-tools/wc

implement-shell-tools/wc/wc.py

Lines changed: 64 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,64 @@
1+
import sys
2+
import os
3+
4+
5+
def main():
6+
args = sys.argv[1:]
7+
flags = []
8+
addresses = []
9+
for item in args:
10+
if item[0] == "-":
11+
flags.append(item)
12+
else:
13+
addresses.append(item)
14+
isLinesNumDisplay = "-l" in flags
15+
isWordsNumDisplay = "-w" in flags
16+
isBytesNumDisplay = "-c" in flags
17+
isNoFlags = len(flags) == 0
18+
totalLines = 0
19+
totalWords = 0
20+
totalBytes = 0
21+
for address in addresses:
22+
file = open(address)
23+
fileContent = file.read()
24+
linesNum = countFileLines(fileContent)
25+
wordsNum = countFileWords(fileContent)
26+
bytes = os.path.getsize(address)
27+
totalLines += linesNum
28+
totalWords += wordsNum
29+
totalBytes += bytes
30+
output = " "
31+
if isLinesNumDisplay or isNoFlags:
32+
output += str(linesNum) + " "
33+
if isWordsNumDisplay or isNoFlags:
34+
output += str(wordsNum) + " "
35+
if isBytesNumDisplay or isNoFlags:
36+
output += str(bytes) + " "
37+
print(output + address)
38+
totalOutput = " "
39+
if isLinesNumDisplay or isNoFlags:
40+
totalOutput += str(totalLines) + " "
41+
if isWordsNumDisplay or isNoFlags:
42+
totalOutput += str(totalWords) + " "
43+
if isBytesNumDisplay or isNoFlags:
44+
totalOutput += str(totalBytes) + " "
45+
print(totalOutput + "total")
46+
47+
48+
def countFileLines(fileContent):
49+
lines = fileContent.split("\n")
50+
linesNum = len(lines)
51+
if lines[linesNum - 1] == "":
52+
linesNum -= 1
53+
return linesNum
54+
55+
56+
def countFileWords(fileContent):
57+
fileContent = fileContent.replace("\n", " ")
58+
words = fileContent.split(" ")
59+
words = list(filter(lambda word: word != "", words))
60+
return len(words)
61+
62+
63+
if __name__ == "__main__":
64+
main()

0 commit comments

Comments
 (0)