简体   繁体   English

如何将文件内容作为消息列表返回

[英]How to return the contents of the file as a list of messages

The parameter represents a message file that is already open for reading, and which contains one message per line. 该参数表示一个已打开以供阅读的消息文件,并且每行包含一个消息。

Read and return the contents of the file as a list of messages, in the order in which they appear in the file. 读取消息的内容并将其作为消息列表返回,并按照消息在文件中出现的顺序排列。 Strip the newline from each line. 从每行中删除换行符。

def read_messages(file):
    """
    """
    message = []
    for line in file:
        new_line = line.strip()
        message.append(new_line)
    return message

well, I know this is not the correct answer but I have no idea how can I fix it. 好吧,我知道这不是正确的答案,但是我不知道该如何解决。

Let's see your function step by step: 让我们逐步了解您的功能:

def read_messages(file):

Function read_messages takes a single parameter, file ; 函数read_messages使用单个参数file ; begin function. 开始功能。

    message = []

Let variable message be the empty list ( [] ). 让变量message为空列表( [] )。

    for line in file:

For each line in file , let variable line be such a line. 对于file每一行,令变量line此类行。

        new_line = line.strip()

Let variable new_line be the line variable, with all whitespaces at the beginning and end of it stripped. 令变量new_lineline变量,将其开头和结尾的所有空格都去掉。

        message.append(new_line)

Append new_line to message . new_line附加到message

    return message

Return variable message ; 返回变量message ; end function. 结束功能。

The algorithm is correct (why did you said otherwise?), but can be simplified, first of all, the pattern... 该算法是正确的(为什么不这样说?),但是可以简化,首先是模式...

x = []
for ...:
    something = ...
    x.append(something)
doSomething(x) # Can be `return` too

Can be simplied to a list comprehension. 可以简化为列表理解。 List comprehensions are a means for constructing a list in a simple and easy to read expression, without doing all the hassle to create the list, adding to it, and returning it. 列表推导是一种以简单易读的表达式构造列表的方法,而无需花费所有麻烦来创建列表,添加列表并返回它。 According to the previous pattern, you can do something like... 根据以前的模式,您可以执行类似...

doSomething([ something for ... ])

That's the same as the pattern above! 与上面的模式相同! Now, applied to your code: 现在,将其应用于您的代码:

return [ ??? for line in file ]

What should we put instead of ??? 我们应该放什么而不是??? there? 那里? Well, you must put the code that calculates new_line ( line.strip() ) of course! 好吧,您当然必须放置计算new_lineline.strip() )的代码! That's because new_line can be tought of as a synonym for line.strip() , as line.strip() has no side effects (doing line.strip() will always give the same result regardless of the time at which it's called, given that line is the same). 这是因为new_line可以作为line.strip()的同义词来line.strip() ,因为line.strip()没有副作用(这样做line.strip()始终会得到相同的结果,而不管调用它的时间如何,给定该line是相同的)。 So... 所以...

return [ line.strip() for line in file ]

You can use that, or if you don't want to lose the whitespace at the beginning, then... 您可以使用它,或者如果您不想在一开始就失去空白,那么...

return [ line.rstrip() for line in file ]

rstrip() does the same as strip() , except that it does not removes whitespace at the beginning of the string. rstrip()strip()相同,但rstrip()不会删除字符串开头的空格。

So, your function becomes... 因此,您的功能变为...

def read_messages(file):
    return [ line.rstrip() for line in file ]

That's all according to your requirements, but let's do a few more optimizations! 这些全都可以满足您的要求,但让我们再做一些优化!

If any line is empty, or contains just whitespace, would you want that line to go into the list? 如果任何行为空或仅包含空格,您是否希望该行进入列表? I won't, at least. 至少我不会。 So how would you fix that? 那么,您将如何解决呢? I would take the list comprehension, and filter out all the empty lines, or those made up of just whitespace. 我会理解列表,并过滤掉所有空行或仅由空白组成的行。 So, the thing becomes... 所以,事情变成了...

import string

def read_messages(file):
    return filter(lambda x: not all(map(lambda y: y in string.whitespace, x)), [ line.rstrip() for line in file ])

Now, what's that? 那是什么 First of all, a lambda is like a function that you can declare as an expression anywhere. 首先, lambda就像一个函数,您可以在任何地方将其声明为表达式。 The format is lambda parameters...: return_value . 格式为lambda parameters...: return_value Did you noticed that return_value stuff? 您是否注意到了return_value东西? Well, it happens that lambdas can only contain a single expression, and they implicitly return that expression. 好吧,碰巧的是,lambda只能包含一个表达式,并且它们隐式返回该表达式。 So, for example, lambda x: x + 1 is a function that takes a single parameter x and returns x + 1 . 因此,例如, lambda x: x + 1是一个函数,它接受单个参数x并返回x + 1

Now, we have three new functions: map , filter , and all : 现在,我们有了三个新功能: mapfilterall

  • map(f, list) : Takes a function f and calls f(x) for each x in list , creating another list holding the result of that. map(f, list) :获取函数f并为list每个x调用f(x) ,创建另一个保存该结果的列表。 It's equivalent to [ f(x) for x in list ] . 等效于[ f(x) for x in list ]
  • filter(f, list) : Takes a function f and creates a new list out of list . filter(f, list) :使用函数f并从list创建一个新list For any x in list , if f(x) is True , then x goes into the new list. 对于list任何x ,如果f(x)True ,则x进入新列表。 Otherwise, it is discarded. 否则,将其丢弃。 It's equivalent to [ x for x in list if f(x) ] . 等效于[ x for x in list if f(x) ]
  • all(list) : Takes a list and returns True if all elements in the list are True , False otherwise. all(list) :接受一个列表,并返回True如果列表中的所有元素都是TrueFalse否则。

Finally, string.whitespace is a list of all whitespace characters. 最后, string.whitespace是所有空白字符的列表。

So, this new construct can be said in Plain English? 那么,这个新结构可以用简单的英语说吗? Of course! 当然!

Return a new list made up of each line in the file, with its trailing whitespace removed, if the line is not empty and not all characters in that line are whitespace characters. 如果该行不为空并且该行中的所有字符都不都是空格字符,则返回一个新列表,该列表由文件中的每一行组成,并删除了其尾随空格。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM