pirelius
pirelius

Reputation: 129

Python read char in text until whitespace

I need to create a generator function that will read a word on request char by char from a text file. I'm aware of .split(), but I specifically need char by char until white space.

word = []
with open("text.txt", "r") as file:
    char = file.read(1)
    for char in file:
        if char != " ":
            word.append(char)
file.close()
print(word)

This code does not exactly do what I want :( I don't have much experience in programming...

EDIT: I have a code like this now:

def generator():
word = " "
with open("text.txt", "r") as file:
    file.read(1)
    for line in file:
        for char in line:
            if char != " ":
                word += char
return(word)


def main():
    print(generator())

if __name__ == '__main__':
    main()

And now it pretty much does what I want, it prints out the char one by one, but it does not stop after the whitespace " " and so prints out the whole text without any spaces. So how can I make it stop before the whitespace and jump put of the function?

Upvotes: 4

Views: 18444

Answers (2)

john-hen
john-hen

Reputation: 4866

The following demonstrates a generator function that yields the individual words from the file as delimited by white-space, reading but one character at a time:

def generator(path):
    word = ''
    with open(path) as file:
        while True:
            char = file.read(1)
            if char.isspace():
                if word:
                    yield word
                    word = ''
            elif char == '':
                if word:
                    yield word
                break
            else:
                word += char

# Instantiate the word generator.
words = generator('text.txt')

# Print the very first word.
print(next(words))

# Print the remaining words.
for word in words:
    print(word)

If the text.txt file contains:

First word on first line.
Second              line.

New paragraph.

then the above script outputs:

First
word
on
first
line.
Second
line.
New
paragraph.

It should be noted that the above generator function is unnecessarily complicated, due to the dubitable constraint that the file be read one character at a time. The much more "pythonic" implementation, yielding the same results, would be this:

def generator(path):
    with open(path) as file:
        for line in file:
            for word in line.split():
                yield word

Upvotes: 5

himanshu shekhar
himanshu shekhar

Reputation: 190

for char in file:

This line reads a line not a character.

So you need to do something like this-

for line in file:
    for char in line:

Upvotes: 0

Related Questions