python - 调用 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)...
解决方案
推荐阅读
- javascript - 在 Reactjs 中使用样式化组件而不是 css 模块有什么好处
- javascript - 我应该在 React Router 之外的 URL 中添加参数吗?
- javascript - XML 解析错误:找不到根元素 (django+AJAX)
- reactjs - 在 getDerivedStateFromProps() 中只返回修改后的状态属性是否重要?
- sql - 如何计算表的总行大小
- ruby-on-rails - Gem 'coffee-rails' 加载错误:必须设置 HOME 环境变量(或 HOMEDRIVE 和 HOMEPATH)并指向一个目录
- python - Python if-elif-else 运行时优化
- react-native - 反应原生视频播放器持续时间
- javascript - 如何使用javascript根据另一个数组对象的属性值过滤对象数组
- c# - 形状不被擦除