读一读我——无废话Python(五)列表解析技巧(2)

2020-05-26  本文已影响0人  du1dume

该文涉及到的文本分析都以英文为示例。

我们知道,搜索引擎为文字信息评级是基于用户的查询。搜索引擎会分析用户搜索的文字内容,文字内容又是由一个一个单词组成。有的单词提供了大量的信息,有的则少之又少。比如这些单词是含有大量信息的:

gray(灰色),bear(熊),teacher(老师)

如下单词就信息量少的可怜:

am,is,as,to,a,the,what (助动词,冠词等)

信息量少的原因是,大部分文字内容都包含这些词。

所以要实现一个搜索引擎,过滤出这些信息量少的单词是一个必须完成的任务。一个简单的启发式算法可以过滤出至多还有3个字母的单词。

今天我们的任务就是用列表解析解决这样的问题。

先看看需求:

首选有一段文字内容,创建一个 list,这个 list 中的每一个元素还是一个 list,子 list 中存放的是每一行文字内容的单词,每个单词的字母数量大于三个。

# 文本内容
text_content = '''
Life is a chess-board The chess-board is the world: the pieces are the phenomena of the universe; 
the rules of the game are what we call the laws of nature. The player on the other side is hidden from us. 
We know that his play is always fair, just and patient. 
But also we know, to our cost, that he never overlooks a mistake, or makes the smallest allowance for ignorance.
'''

# 解决方案
result = [[x for x in line.split() if len(x) > 3] for line in text_content.split('\n')]

print(result) 
# [[], ['Life', 'chess-board', 'chess-board', 'world:', 'pieces', 'phenomena', 'universe;'], ['rules', 'game', 'what', 'call', 'laws', 'nature.', 'player', 'other', 'side', 'hidden', 'from'], ['know', 'that', 'play', 'always', 'fair,', 'just', 'patient.'], ['also', 'know,', 'cost,', 'that', 'never', 'overlooks', 'mistake,', 'makes', 'smallest', 'allowance', 'ignorance.'], []]

在解决方案中我们使用了内嵌列表解析表达式:

外部表达式的 context,也就是数据源,存放的是每一行文本的内容;

内部表达式的 context,是遍历外部表达式生成的 list 中的每一个元素,把每一行文本的内容又拆成了一个一个的单词,并且单词的字母数要大于 3。

最后,expression 是恒等函数,也就是不再对内部 context 生成的 list 做处理。

lambda 表达式和 Map 函数

lambda 表达式之前的文章过已经讲过了,map 函数我相信大家已经耳熟能详了。map 函数和 lambda 表达式的组合其实和列表解析有异曲同工之妙。

假设我们有一个字符串列表,我们需要一个 tuple 列表,每一个 tuple 包含两个值,第二个值是字符串本身,第一个值是个 bool 值,表示某个单词是否在字符串中。

解决方案如下:

str_list = [
  "this is xiaoming's house.",
  "there is a tree in front of xiaoming's house.",
  "the tree has some leaves."
]

result = map(lambda a: (True, a) if 'xiaoming' in a else (False, a), str_list)

print(list(result)) # [(True, "this is xiaoming's house."), (True, "there is a tree in front of xiaoming's house."), (False, 'the tree has some leaves.')]

map 函数的第二个参数是个 list,第一个参数是个函数,map 函数的内部会使用这个函数去遍历 list,返回的结果组成一个新的 list。

lambda 表达式所完成的功能就是,如果 xiaoming 在字符串中就返回 (True, 字符串),不在就返回 (False, 字符串)。参数 a 就是后面 list 每次遍历取出的字符串元素。

如果用列表解析如何实现这个功能?大家自己试试吧。

请关注公众号“读一读我”

上一篇下一篇

猜你喜欢

热点阅读