我正在使用一个名为 mincemeat.py 的 map reduce 实现。它包含一个map函数和reduce函数。首先,我会告诉我我想要完成什么。我正在做一个关于大数据的课程,其中有一个编程任务。问题是有数百个文件包含 paperid:::author1::author2::author3:::papertitle 形式的数据
我们必须浏览所有文件并为特定作者提供他使用最多的词。所以我为它写了下面的代码。
import re
import glob
import mincemeat
from collections import Counter
text_files = glob.glob('test/*')
def file_contents(file_name):
f = open(file_name)
try:
return f.read()
finally:
f.close()
datasource = dict((file_name, file_contents(file_name)) for file_name in text_files)
def mapfn(key, value):
for line in value.splitlines():
wordsinsentence = line.split(":::")
authors = wordsinsentence[1].split("::")
# print authors
words = str(wordsinsentence[2])
words = re.sub(r'([^\s\w-])+', '', words)
# re.sub(r'[^a-zA-Z0-9: ]', '', words)
words = words.split(" ")
for author in authors:
for word in words:
word = word.replace("-"," ")
word = word.lower()
yield author, word
def reducefn(key, value):
return Counter(value)
s = mincemeat.Server()
s.datasource = datasource
s.mapfn = mapfn
s.reducefn = reducefn
results = s.run_server(password="changeme")
# print results
i = open('outfile','w')
i.write(str(results))
i.close()
我现在的问题是,reduce 函数必须接收所有作者的作者姓名和他在标题中使用的所有单词。所以我期望像这样的输出
{authorname: Counter({'word1':countofword1,'word2':countofword2,'word3':countofword3,..}).
但我得到的是
authorname: (authorname, Counter({'word1': countofword1,'word2':countofword2}))
有人能说出为什么会这样吗?我不需要帮助来解决问题,我需要帮助才能知道为什么会这样!