Created
May 6, 2014 18:49
-
-
Save andrewsuzuki/d5f9d293020899f99ec5 to your computer and use it in GitHub Desktop.
Counts lines, words, and characters of a file
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python3.1 | |
import os | |
def docount(string): | |
lines = string.split("\n") | |
line_count = len(lines) | |
word_count = 0 | |
char_count = 0 | |
for line in lines: | |
words = line.split() | |
word_count += len(words) | |
char_count += len(line) | |
return { | |
'l': line_count, | |
'w': word_count, | |
'c': char_count, | |
} | |
def countfile(thefile): | |
if os.path.isfile(thefile): | |
counts = docount(open(thefile).read()) | |
print("File has {0} lines, {1} words, {2} characters".format( | |
counts['l'], counts['w'], counts['c'])) | |
return True | |
else: | |
print("File does not exist, try again.") | |
return False | |
counted = False | |
while not counted: | |
if countfile(input('Which file would you like to count?')): | |
counted = True |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment