I have a modual(Is that the right term?)called WordPlay which has severl functions for exercises in Chapter 9 of "How to Think Like a (Python) Programmer". Below is my code for Ex9.3.2, which has the user input a string letters and then searches a .txt file(Attachment) for words that do not contain any of the letters in the string. The function returns the number of word that did not contain any of the letters.

fin = open ('E:/words.txt')

def avoid(word,forbid):
###Function to search word for any letter if list forbid.  Returns True in no letters in word###

    i=0
    answer='True'
    while i<len(forbid):
        if forbid[i] in word:
            answer='False'
            return answer
        else:
            i=i+1
    return answer

def has_none():
###Function to take a string of  letters from the user and search a list of words.  The number of words that do not cotain any of the letters will be given###

    contain=0
    notcontain=0
    input=raw_input("Please input a string of letters i.e. jdheu")
    for line in fin:
        if avoid(line,input)=='True':
            notcontain+=1
        elif avoid(line,input)=='False':
            contain+=1
    print str(notcontain) +" out of " + str(contain+notcontain) + " did not contain the letters " + input

The Problem:
The first time I call the function it run correctly but if I call the function again with a different set of letter I get 0 returned regardless of the string(Below is an example). I am sure the problem is that the .txt file needs to be reloaded, but I do not know the best way to do this, or any way really.

>>> from WordPlay import*
>>> has_none()
Please input a string of letters i.e. jdheuou
50582 out of 113809 did not contain the letters ou
>>> has_none()
Please input a string of letters i.e. jdheuo
0 out of 0 did not contain the letters o
>>>

Thanx in advance for the help! Let me know if any thing is unclear, and I apologize if it is.

Lanier

Attachments
aa
aah
aahed
aahing
aahs
aal
aalii
aaliis
aals
aardvark
aardvarks
aardwolf
aardwolves
aas
aasvogel
aasvogels
aba
abaca
abacas
abaci
aback
abacus
abacuses
abaft
abaka
abakas
abalone
abalones
abamp
abampere
abamperes
abamps
abandon
abandoned
abandoning
abandonment
abandonments
abandons
abas
abase
abased
abasedly
abasement
abasements
abaser
abasers
abases
abash
abashed
abashes
abashing
abasing
abatable
abate
abated
abatement
abatements
abater
abaters
abates
abating
abatis
abatises
abator
abators
abattis
abattises
abattoir
abattoirs
abaxial
abaxile
abbacies
abbacy
abbatial
abbe
abbes
abbess
abbesses
abbey
abbeys
abbot
abbotcies
abbotcy
abbots
abbreviate
abbreviated
abbreviates
abbreviating
abbreviation
abbreviations
abdicate
abdicated
abdicates
abdicating
abdication
abdications
abdomen
abdomens
abdomina
abdominal
abdominally
abduce
abduced
abducens
abducent
abducentes
abduces
abducing
abduct
abducted
abducting
abductor
abductores
abductors
abducts
abeam
abed
abele
abeles
abelmosk
abelmosks
aberrant
aberrants
aberration
aberrations
abet
abetment
abetments
abets
abettal
abettals
abetted
abetter
abetters
abetting
abettor
abettors
abeyance
abeyances
abeyancies
abeyancy
abeyant
abfarad
abfarads
abhenries
abhenry
abhenrys
abhor
abhorred
abhorrence
abhorrences
abhorrent
abhorrer
abhorrers
abhorring
abhors
abidance
abidances
abide
abided
abider
abiders
abides
abiding
abied
abies
abigail
abigails
abilities
ability
abioses
abiosis
abiotic
abject
abjectly
abjectness
abjectnesses
abjuration
abjurations
abjure
abjured
abjurer
abjurers
abjures
abjuring
ablate
ablated
ablates
ablating
ablation
ablations
ablative
ablatives
ablaut
ablauts
ablaze
able
ablegate
ablegates
abler
ables
ablest
ablings
ablins
abloom
abluent
abluents
ablush
abluted
ablution
ablutions
ably
abmho
abmhos
abnegate
abnegated
abnegates
abnegating
abnegation
abnegations
abnormal
abnormalities
abnormality
abnormally
abnormals
abo
aboard
abode
aboded
abodes
aboding
abohm
abohms
aboideau
aboideaus
aboideaux
aboil
aboiteau
aboiteaus
aboiteaux
abolish
abolished
abolishes
abolishing
abolition
abolitions
abolla
abollae
aboma
abomas
abomasa
abomasal
abomasi
abomasum
abomasus
abominable
abominate
abominated
abominates
abominating
abomination
abominations
aboon
aboral
aborally
aboriginal
aborigine
aborigines
aborning
abort
aborted
aborter
aborters
aborting
abortion
abortions
abortive
aborts
abos
abought
aboulia
aboulias
aboulic
abound
abounded
abounding
abounds
about
above
aboveboard
aboves
abracadabra
abradant
abradants
abrade
abraded
abrader
abraders
abrades
abrading
abrasion
abrasions
abrasive
abrasively
abrasiveness
abrasivenesses
abrasives
abreact
abreacted
abreacting
abreacts
abreast
abri
abridge
abridged
abridgement
abridgements
abridger
abridgers
abridges
abridging
abridgment
abridgments
abris
abroach
abroad
abrogate
abrogated
abrogates
abrogating
abrupt
abrupter
abruptest
abruptly
abscess
abscessed
abscesses
abscessing
abscise
abscised
abscises
abscisin
abscising
abscisins
abscissa
abscissae
abscissas
abscond
absconded
absconding
absconds
absence
absences
absent
absented
absentee
absentees
absenter
absenters
absenting
absently
absentminded
absentmindedly
absentmindedness
absentmindednesses
absents
absinth
absinthe
absinthes
absinths
absolute
absolutely
absoluter
absolutes
absolutest
absolution
absolutions
absolve
absolved
absolver
absolvers
absolves
absolving
absonant
absorb
absorbed
absorbencies
absorbency
absorbent
absorber
absorbers
absorbing
absorbingly
absorbs
absorption
absorptions
absorptive
abstain
abstained
abstainer
abstainers
abstaining
abstains
abstemious
abstemiously
abstention
abstentions
absterge
absterged
absterges
absterging
abstinence
abstinences
abstract
abstracted
abstracter
abstractest
abstracting
abstraction
abstractions
abstractly
abstractness
abstractnesses
abstracts
abstrict
abstricted
abstricting
abstricts
abstruse
abstrusely
abstruseness
abstrusenesses
abstruser
abstrusest
absurd
absurder
absurdest
absurdities
absurdity
absurdly
absurds
abubble
abulia
abulias
abulic
abundance
abundances
abundant
abundantly
abusable
abuse
abused
abuser
abusers
abuses
abusing
abusive
abusively
abusiveness
abusivenesses
abut
abutilon
abutilons
abutment
abutments
abuts
abuttal
abuttals
abutted
abutter
abutters
abutting
abuzz
abvolt
abvolts
abwatt
abwatts
aby
abye
abyed
abyes
abying
abys
abysm
abysmal
abysmally
abysms
abyss
abyssal
abysses
acacia
acacias
academe
academes
academia
academias
academic
academically
academics
academies
academy
acajou
acajous
acaleph
acalephae
acalephe
acalephes
acalephs
acanthi
acanthus
acanthuses
acari
acarid
acaridan
acaridans
acarids
acarine
acarines
acaroid
acarpous
acarus
acaudal
acaudate
acauline
acaulose
acaulous
accede
acceded
acceder
acceders
accedes
acceding
accelerate
accelerated
accelerates
accelerating
acceleration
accelerations
accelerator
accelerators
accent
accented
accenting
accentor
accentors
accents
accentual
accentuate
accentuated
accentuates
accentuating
accentuation
accentuations
accept
acceptabilities
acceptability
acceptable
acceptance
acceptances
accepted
acceptee
acceptees
accepter
accepters
accepting
acceptor
acceptors
accepts
access
accessed
accesses
accessibilities
accessibility
accessible
accessing
accession
accessions
accessories
accessory
accident
accidental
accidentally
accidentals
accidents
accidie
accidies
acclaim
acclaimed
acclaiming
acclaims
acclamation
acclamations
acclimate
acclimated
acclimates
acclimating
acclimation
acclimations
acclimatization
acclimatizations
acclimatize
acclimatizes
accolade
accolades
accommodate
accommodated
accommodates
accommodating
accommodation
accommodations
accompanied
accompanies
accompaniment
accompaniments
accompanist
accompany
accompanying
accomplice
accomplices
accomplish
accomplished
accomplisher
accomplishers
accomplishes
accomplishing
accomplishment
accomplishments
accord
accordance
accordant
accorded
accorder
accorders
according
accordingly
accordion
accordions
accords
accost
accosted
accosting
accosts
account
accountabilities
accountability
accountable
accountancies
accountancy
accountant
accountants
accounted
accounting
accountings
accounts
accouter
accoutered
accoutering
accouters
accoutre
accoutred
accoutrement
accoutrements
accoutres
accoutring
accredit
accredited
accrediting
accredits
accrete
accreted
accretes
accreting
accrual
accruals
accrue
accrued
accrues
accruing
accumulate
accumulated
accumulates
accumulating
accumulation
accumulations
accumulator
accumulators
accuracies
accuracy
accurate
accurately
accurateness
accuratenesses
accursed
accurst
accusal
accusals
accusant
accusants
accusation
accusations
accuse
accused
accuser
accusers
accuses
accusing
accustom
accustomed
accustoming
accustoms
ace
aced
acedia
acedias
aceldama
aceldamas
acentric
acequia
acequias
acerate
acerated
acerb
acerbate
acerbated
acerbates
acerbating
acerber
acerbest
acerbic
acerbities
acerbity
acerola
acerolas
acerose
acerous
acers
acervate
acervuli
aces
acescent
acescents
aceta
acetal
acetals
acetamid
acetamids
acetate
acetated
acetates
acetic
acetified
acetifies
acetify
acetifying
acetone
acetones
acetonic
acetose
acetous
acetoxyl
acetoxyls
acetum
acetyl
acetylene
acetylenes
acetylic
acetyls
ache
ached
achene
achenes
achenial
aches
achier
achiest
achievable
achieve
achieved
achievement
achievements
achiever
achievers
achieves
achieving
achiness
achinesses
aching
achingly
achiote
achiotes
achoo
achromat
achromats
achromic
achy
acicula
aciculae
acicular
aciculas
acid
acidhead
acidheads
acidic
acidified
acidifies
acidify
acidifying
acidities
acidity
acidly
acidness
acidnesses
acidoses
acidosis
acidotic
acids
acidy
acierate
acierated
acierates
acierating
aciform
acinar
acing
acini
acinic
acinose
acinous
acinus
acknowledge
acknowledged
acknowledgement
acknowledgements
acknowledges
acknowledging
acknowledgment
acknowledgments
aclinic
acmatic
acme
acmes
acmic
acne
acned
acnes
acnode
acnodes
acock
acold
acolyte
acolytes
aconite
aconites
aconitic
aconitum
aconitums
acorn
acorns
acoustic
acoustical
acoustically
acoustics
acquaint
acquaintance
acquaintances
acquaintanceship
acquaintanceships
acquainted
acquainting
acquaints
acquest
acquests
acquiesce
acquiesced
acquiescence
acquiescences
acquiescent
acquiescently
acquiesces
acquiescing
acquire
acquired
acquirer
acquirers
acquires
acquiring
acquisition
acquisitions
acquisitive
acquit
acquits
acquitted
acquitting
acrasin
acrasins
acre
acreage
acreages
acred
acres
acrid
acrider
acridest
acridine
acridines
acridities
acridity
acridly
acridness
acridnesses
acrimonies
acrimonious
acrimony
acrobat
acrobatic
acrobats
acrodont
acrodonts
acrogen
acrogens
acrolein
acroleins
acrolith
acroliths
acromia
acromial
acromion
acronic
acronym
acronyms
across
acrostic
acrostics
acrotic
acrotism
acrotisms
acrylate
acrylates
acrylic
acrylics
act
acta
actable
acted
actin
actinal
acting
actings
actinia
actiniae
actinian
actinians
actinias
actinic
actinide
actinides
actinism
actinisms
actinium
actiniums
actinoid
actinoids
actinon
actinons
actins
action
actions
activate
activated
activates
activating
activation
activations
active
actively
actives
activism
activisms
activist
activists
activities
activity
actor
actorish
actors
actress
actresses
acts
actual
actualities
actuality
actualization
actualizations
actualize
a

First of all, please use the Python style guide by GVR himself:
http://www.python.org/peps/pep-0008.html
To make code easier to read.

I used a different Words.txt, but this should work ...

# WordPlay.py
# saved the module in D:\Python25\Atest\Bull
# use sys.path.append(r'D:\Python25\Atest\Bull') so PYTHONPATH can find it

def avoid(word, forbid):
    """
    Function to search word for any letter if list forbid.
    Returns True if no letters in word
    """
    i = 0
    answer = True
    while i < len(forbid):
        if forbid[i] in word:
            answer = False
            return answer
        else:
            i = i + 1
    return answer

def has_none():
    """
    Function to take a string of letters from the user and search a list of words.
    The number of words that do not cotain any of the letters will be returned.
    """
    contain = 0
    notcontain = 0
    my_input = raw_input("Please input a string of letters (i.e. jdheu): ")
    for line in file(r'D:\Python25\Atest\Bull\Words.txt'):
        if avoid(line, my_input) == True:
            notcontain += 1
        elif avoid(line, my_input) == False:
            contain += 1
    print str(notcontain) + "words out of " + str(contain + notcontain) + \
        " did not contain the letters " + my_input
    
# test the module
if __name__ == '__main__':
    has_none()

The Python shell results ...

>>> import sys, os
>>> sys.path.append(r'D:\Python25\Atest\Bull')
>>> from WordPlay import *
>>> has_none()
Please input a string of letters (i.e. jdheu): aeui
1980words out of 74744 did not contain the letters aeui
>>> has_none()
Please input a string of letters (i.e. jdheu): aeui
1980words out of 74744 did not contain the letters aeui
>>>

The problem is line 2
fin = open ('E:/words.txt')
You open the file as a global and in line 23 process each record in the file via a for() loop, leaving the pointer at the end of the file. So the second time through you read the file starting at the end of the file, that is no records are read. You can use vegaseat's solution, or move the open into the function and then close the file (which does the same thing as vegaseat). That is somewhat inefficient since you read the same file every time the function is called but if the file is not large it is not much of a difference. has_none() would become

def has_none():

###Function to take a string of letters from the user and search a list of words. 
##The number of words that do not cotain any of the letters will be given###

     contain=0
     notcontain=0

     input=raw_input("Please input a string of letters i.e. jdheu")

     fin = open ('E:/words.txt')
     for line in fin:
          if avoid(line,input)=='True':
               notcontain+=1
          elif avoid(line,input)=='False':
               contain+=1
     fin.close()
     print str(notcontain) +" out of " + str(contain+notcontain) + " did not contain the letters " + input

Woooee is right. When you read a file line-by-line in a loop, it stops once it encounters EOF. Hence, you find nothing after that.

You can use seek(0) method of file handler to seek or move file-pointer to start of the file, without having to open and close the file recurssively.

>>> f = open("C:\\Documents and Settings\c5090455\Desktop\A.pm")
>>> f.tell()  # current position of the file pointer, now start of the file
0L
>>> f.read()
'\n# A.pm\npackage A;\nuse warnings;'
>>> f.tell()  # current position of the file, now EOF
361L
>>f.seek(0)  # move file pointer to start of the file.
>>> f.read()
'\n# A.pm\npackage A;\nuse warnings;'
>>f.close()
>>

katharnakh

Edited 3 Years Ago by diafol: fixed formatting

This question has already been answered. Start a new discussion instead.