【问题标题】:Return one word at a time一次返回一个单词
【发布时间】:2020-06-01 01:03:31
【问题描述】:

我有一个函数,它接收一个文本文件并一个一个地打印文件中的每个单词,每个单词都在一个新行上。


这是我上面所说的代码:

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() 函数会将以下内容打印到标准输出(按格式):

stack,  
hello  
test  
python's  
name

目标是将每个单词一个一个地传递给第二个函数,该函数将对它执行一些操作(例如:将第一个字母大写)。然而,最重要的部分是它只向第二个函数发送一个词,一旦执行操作,就发送下一个词。

为此,我将print 替换为return,在意识到这行不通(只会发送一个字)之后,我尝试使用yield。但是,它仍然只向第二个函数发送一个单词然后停止(它不会继续发送以下单词)。

我还尝试了除当前方法之外的方法(创建一个单词列表,打印该列表而不进行格式化,然后清除该列表),例如简单地打印word 等等。不幸的是,我得到了同样的结果;我可以一次打印每个单词,但不能一次将每个单词发送到第二个函数。

有人有什么建议吗?提前致谢。

为清楚起见进行编辑:
第二个函数接受一个参数,我使用第一个函数作为参数。
示例:

def operation(script):
    does some things

operation(print_one_word())

【问题讨论】:

  • 您可以通过加载到列表words = list(print_one_word()) 来使用yield 并将该列表传递给第二个函数或for word in words: function...
  • 还是不明白为什么要在列表中添加一个单词然后清除该列表?

标签: python function text-files


【解决方案1】:

只需将所有单词存储到一个列表中,然后调用您想要的任何函数(在这种情况下,我会在之后对它们调用 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()

输出:

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

【讨论】:

    【解决方案2】:

    这是一个如何从函数返回列表和 yield 的示例,请记住 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)
    

    输出:

    listed this
    listed is
    listed a
    listed test
    listed hello
    listed there
    yielded this
    yielded is
    yielded a
    yielded test
    yielded hello
    yielded there
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-10-10
      • 1970-01-01
      • 2018-05-14
      • 2023-03-15
      • 2012-09-23
      相关资源
      最近更新 更多