Scanning a file character by character

Gabriel Genellina gagsl-py2 at yahoo.com.ar
Thu Feb 5 12:16:03 EST 2009


En Thu, 05 Feb 2009 04:48:13 -0200, Spacebar265 <spacebar265 at gmail.com>
escribió:

> Hi. Does anyone know how to scan a file character by character and
> have each character so I can put it into a variable. I am attempting
> to make a chatbot and need this to read the saved input to look for
> spelling mistakes and further analysis of user input.

Read the file one line at a time, and process each line one character at a
time:

with open(filename, "r") as f:
    for line in f:
      for c in line:
        process(c)

But probably you want to process one *word* at a time; the easiest way
(perhaps inaccurate) is to just split on whitespace:

    ...
      for word in line.split():
        process(word)

-- 
Gabriel Genellina




More information about the Python-list mailing list