def process_story(raw_story):
nonempty_lines = list(filter(lambda x: len(x) != 0, [line.strip() for line in raw_story.split("\n")]))
# for some unknown reason some lines miss a period, add it
nonempty_lines = [_add_missing_period(line) for line in nonempty_lines]
# gather article lines
story_lines = []
lines = deque(nonempty_lines)
while True:
try:
element = lines.popleft()
if element.startswith("@highlight"):
break
story_lines.append(element)
except IndexError:
# if "@highlight" is absent from the file we pop
# all elements until there is None, raising an exception.
return story_lines, []
# gather summary lines
summary_lines = list(filter(lambda t: not t.startswith("@highlight"), lines))
return story_lines, summary_lines
内容处理函数
首先将非空行筛选出,变量nonempty_lines=list()
非空行为一个列表
使用filter筛选过滤元素,strip()用于移除字符串头尾指定的字符(默认为空格或换行符)或字符序列
line 是raw_story中的行,使用split以换行符分隔(raw_story为上一模块中的输出)
【 nonempty_lines = [_add_missing_period(line) for line in nonempty_lines],_add_missing_period为一个增加缺失的符号的函数,具体在下个详解】
新建变量story_lines = []故事行,类型为列表
lines = deque(nonempty_lines)
lines变量使用deque模块将上面的非空行列表变为两端列表
while True:
try:
element = lines.popleft()
if element.startswith("@highlight"):
break
story_lines.append(element)
except IndexError:
# if "@highlight" is absent from the file we pop
# all elements until there is None, raising an exception.
return story_lines, []
使用while true循环,将element等于lines的左端元素,设定终止条件为字符元素是否为@highlight,因为摘要以@highlight开头,只提取故事。
story_lines.append(element)将提取到的元素赋予故事行
except IndexError,如果出现错误就返回错误
运行结束,返回故事行
此时的lines行中只剩@highlight与摘要
summary_lines = list(filter(lambda t: not t.startswith("@highlight"), lines))
使用filter与lamdba结合,筛选出摘要行
return story_lines, summary_lines
返回故事与摘要
——————————————————————————————————————
filter(function,iterable)
function -- 判断函数。
iterable -- 可迭代对象
常常和lambda连用,lamdba是一个匿名函数,只接受一个表达式
例:
a=list(filter(lamdba(x):x=2,(1,12,2,2,2,3)))
print(a)
输出
(2,2,2)
-----------------------------------------------------------------------------------------------------------------------------
deque模块是python标准库collections中的一项,它提供了两端都可以操作的序列,这意味着,在序列的前后你都可以执行添加或删除操作
默认的append是从列表最后即最右添加,而双端操作的可以使用appendleft从最左端添加
对应的提取有pop,与popleft
Python deque用法介绍_hanson-leung的博客-CSDN博客_deque python
---------------------------------------------------------------------------------------------------------------------------------
startswith(str)判断开头是否为字符str
endswith(str)判断结尾是否为字符str
——————————————————————————————————————