Python在文本中读取char直到空格

时间:2014-11-06 11:14:14

标签: python-3.x

我需要创建一个生成器函数,它将通过文本文件中的char读取请求char上的单词。我知道.split(),但我特别需要char by char直到空格。

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)

这段代码并不完全符合我的要求:(我在编程方面没有太多经验......

编辑:我现在有这样的代码:

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()

现在它几乎可以做我想要的东西,它逐个打印掉char,但它不会在空格“”之后停止,因此打印出整个文本而没有任何空格。那么如何才能让它在空白和跳转功能之前停止?

2 个答案:

答案 0 :(得分:0)

for char in file:

此行读取的行不是字符。

所以你需要做这样的事情 -

for line in file:
    for char in line:

答案 1 :(得分:0)

下面的示例演示了一个generator函数,该函数从文件中产生用空格分隔的单个单词,一次只能读取一个字符:

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)

如果text.txt文件包含:

First word on first line.
Second              line.

New paragraph.

然后上述脚本输出:

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

应该注意的是,上述generator函数不必要地复杂,这是由于可双重约束的约束,即一次只能读取一个字符的文件。 yield实现更多结果的“ pythonic”实现将是这样:

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