Python:如何从文本中检索第二个单词

时间:2014-11-06 19:28:03

标签: python

因此,生成器函数通过char生成单词char,直到""现在我希望main函数调用100次生成器函数,以便创建一个包含100个单词的列表单词。正如我现在所说的那样,它将调出函数100x,但只能用一个字。我应该怎么做才能记住它已经使用过的单词。

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

def main():
    words = []
    for i in range(100):
        generator()
        words.append(word)
    print(words)

if __name__ == '__main__':
    main()

2 个答案:

答案 0 :(得分:1)

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

现在是一个发电机

它像这样使用

for word in word_generator():
   print word

如果你只想要你可以做的前一百个

for i,word in enumerate(word_generator()):
    if i > 100: 
      break
    print word
print "Last Word:",word

答案 1 :(得分:1)

您可以使用yield创建一个生成器,并根据需要操作生成器(例如,在100处停止)。

def make_generator():
    with open("text.txt", "r") as f:
        for line in f:
            for word in line.split():
                yield word

def main():
    words = []
    generator = make_generator()
    for i in range(100):
        w = next(generator)
        words.append(w)
    print(words)

if __name__ == '__main__':
    main()