[View]  [Edit]  [Lock]  [References]  [Attachments]  [History]  [Home]  [Changes]  [Search]  [Help] 

WordCounter class source code

Object
	subclass: #WordCounter
	instanceVariableNames: 'bookPath chapterNamePrefix'
	category: #sample !

"accessing"

! WordCounter methodsFor: #accessing !
bookPath
	" Return the bookPath of the receiver where find the chapters. "

	^bookPath! !

! WordCounter methodsFor: #accessing !

bookPath: aString
	" Set the bookPath of the receiver. "

	bookPath := aString! !

! WordCounter methodsFor: #accessing !
chapterNamePrefix
	" Return the chapterNamePrefix of the receiver. "

	^ chapterNamePrefix! !

! WordCounter methodsFor: #accessing !

chapterNamePrefix: aString
	" Set the chapterNamePrefix of the receiver. "

	chapterNamePrefix := aString! !


"initializing"


! WordCounter methodsFor: #initialize !
initialize
	" Private - Initialize the receiver. "
	super initialize.
	self bookPath: 'book/'.
	self chapterNamePrefix:'chapter-'.! !

! WordCounter class methodsFor: #launching !
launch
	" Private - Launch. "
	|counter|

	counter := self new.
	counter bookPath:'Alice in Wonderland/'.
	self print: 'The entire book has ', counter countWordsInBookFolder asString, ' words'.! !

! WordCounter methodsFor: #counting !
countWords: aString
	" returns the amount of words in aString "
	^aString asArrayOfSubstrings size.! !


! WordCounter methodsFor: #counting !
countWordsInFile: aFileName
	" returns the amount of words in a file named aFileName or nil if the file does not exist. "
	|answer|
	contents := aFileName fileContents.
	contents isNil ifTrue: [^nil].
	answer := self countWords: contents.
	self print: aFileName, ' has ', answer asString, ' words' , ' and ', contents size asString ,' characters'.

	^self countWords: contents.! !


! WordCounter methodsFor: #counting !
countWordsInFolder: aBookFolderPathName withChapterPrefix: aChapterPrefix
	" returns the number of words in all the chapters at the given book folder "
	"It assumes: - All  the chapters are in the same given folder
		     - All the chapters are named <prefix>1.txt, <prefix>2.txt, ...and so on ( for example chapter-1.txt, chapter-2.txt, chapter-3.txt, and so on
		     - The names list starts appending the integer 1 to the shared prefix, and does not skip any number. "

	|answer chapterIndex chapterContents wordsCountInChapter|

	answer := 0.
	chapterIndex := 1.
	[|fileName | 
		fileName := aBookFolderPathName, aChapterPrefix,chapterIndex asString, '.txt'.
		wordsCountInChapter := self countWordsInFile: fileName.
		wordsCountInChapter notNil or:[ wordsCountInChapter == 0]
	] whileTrue:[
			answer := answer + wordsCountInChapter.
			chapterIndex := chapterIndex + 1.
	].
	^answer.! 

! WordCounter methodsFor: #counting !
countWordsInBookFolder
^self countWordsInFolder: self bookPath withChapterPrefix: self chapterNamePrefix. ! !