首页 > 解决方案 > 调用 flatMap 中的函数,以应用于文本文件的每一行

问题描述

我打算用 Spark 做一些基本的自然语言处理。我得到了一个文本文件,我需要从中进行一些基本的转换以从文件中输出词性。我想使用 flatMap 在文本文件的每一行上应用 pos_tag_counter 函数,以将词性分配给每行中的单词,但我无法让 lambda 函数逐行拆分文件。相反,它是按字分割的。这是我到目前为止所拥有的。前三行删除空行和以 'URL' 开头的行:

import re

reg = re.compile('^(?!URL).*')
non_empty_lines = text.filter(lambda x: len(x)>0)
no_urls = non_empty_lines.filter(lambda x: reg.match(x))

phrases = no_urls.flatMap(lambda line: pos_tag_counter(line))
part_of_speech = phrases.map(lambda word: (word[1],1))

pos = part_of_speech.reduceByKey(lambda accumulator,value: accumulator + value)

flatMap 中的 pos_tag_counter 函数对行进行标记并找到构成词性的词组。flatMap 调用应该返回如下内容:

[('events of the day', 'NP')...]

带有一个元组列表,该列表完全封装了文本文件中的每个语音部分。但是,当我运行 phrases.take(5) 时,我得到的是被分配为词性的单数词:

[('WASHINGTON', 'NNP'),
 ('Stellar', 'NNP'),
 ('pitching', 'NN'),
 ('kept', 'VBD'),
 ('the', 'DT'),
 ('Mets', 'NNPS'),
 ('afloat', 'NN'),
 ('in', 'IN'),
 ('the', 'DT'),
 ('first', 'JJ'),
 ('half', 'NN'),
 ('of', 'IN'),
 ('last', 'JJ'),
 ('season', 'NN'),
 ('despite', 'IN')]

最终,我需要获取正确的列表并累积最常见的词类类型并按降序排序。最终输出将如下所示:

[('NN', 5628),
 ('IN', 4690),
 ('NNP', 4575),
 ('DT', 3913),
 ('JJ', 2550),
 ('NNS', 2345)...

标签: pythonpandas

解决方案


推荐阅读