我有两个文件,我需要计算两个文件中的单词数,以及每个单词的文件名。
doc1。txt=“我有一个苹果”,doc2。txt=“我住在公寓里”。
现在我想做MapReduce,输出如下:
((单词、文件名)、计数)。
示例:((apple,doc1.txt),1)
#!/usr/bin/env python
导入系统
导入glob
#从字符串导入标点符号
#---从stdin获取所有线路---
对于系统中的行。标准文本:
#---删除前导和尾随空格---
#直线。翻译(无,标点符号)。带('\t')
直线。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")
此代码每次都会打印每个文档中的所有单词,但对于这两个文档,它们会在每个单词中指定每个文档的名称,如下所示:
(苹果,doc1.txt),1
(苹果,doc2.txt),1