python - 从一组文档中,如何在 python 中为 Mapreduce 计算单词、文档数和计数
问题描述
我有两个文档,我需要计算两个文档中的单词数,以及每个单词的文档名称。doc1.txt = "我有一个苹果", doc2.txt = "我住在公寓里"。现在我想做 MapReduce,输出看起来像这样:((word, document name),count)。示例:((apple, doc1.txt),1)
#!/usr/bin/env python
import sys import glob #from string import punctuation #--- 从 stdin 获取所有行 --- for line in sys. stdin: #--- 删除前导和尾随空格--- #line=line.translate(None, punctuation).strip('\t') line = line.strip()
#--- split the line into words ---
words = line.split()
doc_name = glob.glob("*.txt")
for doc in doc_name:
print(doc)
if doc[] == '':
for word in words:
#word = word.rstrip()
key = word+ ',' +doc
#print '%s\t%s' % (key, "1")
此代码每次都会打印每个文档中的所有单词,但是对于两个文档,它们会在每个单词中分配每个文档名称,如下所示: (apple, doc1.txt),1 (apple, doc2.txt),1
解决方案
推荐阅读
- sql - 无法将表格导出为 csv 格式
- css - 当 0 值没有单位时如何验证 CSS
- database - 如何在flutter firebase中获取具有用户ID的谷歌用户对象?
- swift - 如何在 swift 中使用字典解析 json?
- android - Android MediaExtractor:读取 mp3 文件时速度慢
- c++ - 为什么我会收到此错误:CSE 类没有名为 EnterRN 和 EnterName 的成员?
- java - Android Studio 接受许可
- amazon-web-services - AWS Fargate 定价任务
- java - 尝试合并arraylist时不断收到IndexOutOfBounds异常
- python - 关于python离散卷积的问题