|
| 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