Skip to content

Commit 9bc06ec

Browse files
committed
refactoring
1 parent 558abe6 commit 9bc06ec

File tree

1 file changed

+22
-24
lines changed
  • implement-shell-tools/wc

1 file changed

+22
-24
lines changed

implement-shell-tools/wc/wc.py

Lines changed: 22 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -11,23 +11,15 @@
1111

1212
args = parser.parse_args()
1313

14-
15-
count_total_lines = 0
16-
count_total_words = 0
17-
count_total_bytes = 0
18-
19-
for file_path in args.path:
20-
with open(file_path, "r") as file:
21-
content = file.read()
14+
def calculate_counts(content):
2215

2316
count_lines = content.count("\n")
2417
count_words = len(content.split())
2518
count_bytes = len(content.encode("utf-8"))
19+
20+
return count_lines, count_words, count_bytes
2621

27-
count_total_lines += count_lines
28-
count_total_words += count_words
29-
count_total_bytes += count_bytes
30-
22+
def format_output(count_lines, count_words, count_bytes, file_path):
3123
if not (args.l or args.w or args.c):
3224
print(count_lines, count_words, count_bytes, file_path)
3325
else:
@@ -40,16 +32,22 @@
4032
line += f"{count_bytes} "
4133
line += f"{file_path}"
4234
print(line)
35+
36+
count_total_lines = 0
37+
count_total_words = 0
38+
count_total_bytes = 0
39+
40+
for file_path in args.path:
41+
with open(file_path, "r") as file:
42+
content = file.read()
43+
44+
count_lines, count_words, count_bytes = calculate_counts(content)
45+
46+
count_total_lines += count_lines
47+
count_total_words += count_words
48+
count_total_bytes += count_bytes
49+
50+
format_output(count_lines, count_words, count_bytes, file_path)
51+
4352
if len(args.path) > 1:
44-
if not (args.l or args.w or args.c):
45-
print(count_total_lines, count_total_words, count_total_bytes, " total")
46-
else:
47-
line = ""
48-
if args.l:
49-
line += f"{count_total_lines} "
50-
if args.w:
51-
line += f"{count_total_words} "
52-
if args.c:
53-
line += f"{count_total_bytes} "
54-
line += " total"
55-
print(line)
53+
format_output(count_total_lines, count_total_words, count_total_bytes, " total")

0 commit comments

Comments
 (0)