每次只返回一个字

问题描述 投票:1回答:2

我有一个函数,它接收一个文本文件,并将文件中的每个字逐一打印出来,每个字都在新的行上。


下面是做我上面说的代码。

def print_one_word():
    with open("test_script.txt", "r") as f:
        lines = f.readlines()
        word_current = []
        for line in lines:
            for word in line.split():
                word_current.append(word)
                print("".join(word_current))
                word_current.clear()

例子,在指定的文本文件内容下:

test_script.txt 有内容(格式化)。stack, hello test python's name

这个函数 print_one_word() 将打印以下内容到stdout(格式化)。

stack,  
hello  
test  
python's  
name

我们的目标是把每个单词一个一个地传给第二个函数,由它来执行一些操作(例如:把第一个字母大写)。然而,我们的目标是将每个单词逐一传入第二个函数,并对其进行一些操作(例如:将第一个字母大写)。重中之重 是它只向第二个函数发送一个字,一旦执行了操作,就会发送下一个字。

为了做到这一点,我将 printreturn在意识到这样做行不通(只能发送一个字)之后,我尝试使用了 yield. 但是,它仍然只向第二个函数发送一个单词,然后就停止了(不会继续发送下面的单词)。

除了目前的方法外,我还试过其他方法(创建一个单词列表,打印该列表而不进行格式化,然后清除该列表),如简单地打印出 word 诸如此类。不幸的是,我得到的结果是一样的,我可以把每个字一个个打印出来,但不能把每个字一个个发送到第二个函数中。

有人有什么建议吗?先谢谢大家了。

编辑,为了清楚起见。 第二个函数接收一个参数,我用第一个函数作为参数。例如:我有一个函数,它接收一个参数,我使用第一个函数作为参数。

def operation(script):
    does some things

operation(print_one_word())

python function text-files
2个回答
3
投票

只需将所有的单词存储到一个列表中,然后调用任何你想要的函数(在本例中,我调用的是 do_something() 之后对其。

def do_something(word):
  print(word.upper())

def print_one_word():
    with open("test_script.txt", "r") as f:
        lines = f.readlines()
        all_words = []
        for line in lines:
            for word in line.split():
                all_words.append(word)
                print(word)

    for word in all_words:
      do_something(word)

print_one_word()

output:

stack,
hello
test
python's
name
STACK,
HELLO
TEST
PYTHON'S
NAME

1
投票

下面是一个关于如何从函数中返回列表和收益的例子,请记住: yield 返回一个生成器对象,如果你想重复使用产生的结果,你需要将它们列表。

def yield_words():
    with open("test_script.txt", "r") as f:
        lines = f.readlines()
        for line in lines:
            for word in line.split():
                yield word

def list_words():
    with open("test_script.txt", "r") as f:
        return [word
                for line in f.readlines()
                for word in line.split()]

def operation(prefix, word):
    print(f'{prefix} {word}')

yielded_words = list(yield_words())
listed_words = list_words()

for word in listed_words:
    operation('listed', word)

for word in yielded_words:
    operation('yielded', word)

Output:

listed this
listed is
listed a
listed test
listed hello
listed there
yielded this
yielded is
yielded a
yielded test
yielded hello
yielded there
© www.soinside.com 2019 - 2024. All rights reserved.