beginner's question

Sean Ross sross at connectmail.carleton.ca
Fri May 14 09:04:50 EDT 2004


"Hadi" <hadi at nojunk.com.au> wrote in message
news:c82d51$78s$1 at lust.ihug.co.nz...
> Hi,
> I have two files and the array that contains 20 words in it.
> I'm trying to write python script that suppose achieve the following:
> -Open file-1, read the line that contains 20 words separated with commas
> -Compare each word with words in the array
> -Open file-2
> -if the word appears in the array write 'true' in file-2
> -if not write 'false'
> -repeat this for every line in the file-1
>
> so, two file will be identical in terms of number of lines and number of
> words in each line.
> However, file-2 will only contain wods 'true' and 'false'.
>
> Can anyone give some example or point me to som useful web sites please.
>
> Thanks,
> hadi
>
>

lexicon = ["our", "list", "of", "words", "to", "be", "compared"]

# open the source and destination files
src = file("file1/path")           # open for reading
dst = file("file2/path", 'w')     # open for writing

# Hadi: does file1 contain one or more lines? This only works for one line.
# For more lines, you'll need to do further processing ...
#
# Make a list of the words in src. We split the line at each comma, and
# remove any excess whitespace from around the word
words = [w.strip() for w in src.readline().split(',')]

# Now we see if the words are in our list and write the results to dst
for w in words:
    dst.write(str(w in lexicon))    # writes 'True, ' or 'False, '

# Python will eventually close the files for you, or you can do it
explicitly
src.close()
dst.close()



Hope that helps,

Sean





More information about the Python-list mailing list