控制python输出到控制台

ezykj2lf  于 2021-06-02  发布在  Hadoop
关注(0)|答案(1)|浏览(459)

我正在使用hadoop/mapreduce构建一个电影推荐。
现在我只使用python来实现mapreduce过程。
所以我基本上是分别运行每个Map器和reducer,并使用从Map器到reducer的控制台输出。
我遇到的问题是python在终端中以字符串的形式输出值,因此如果我使用数字,则数字将以字符串的形式打印,这使得很难简化过程,因为转换过程会在服务器上增加更多的负载。
因此,如何解决这个问题,我希望使用纯python实现它,而不使用第三方lib。

import sys

def mapper():
    '''
        From Mapper1 : we need only UserID , (MovieID , rating)
        as output.
    '''

    #* First mapper

    # Read input line
    for line in sys.stdin:
        # Strip whitespace and delimiter - ','
        print line
        data = line.strip().split(',')

        if len(data) == 4:
            # Using array to print out values
            # Direct printing , makes python interpret
            # values with comma in between as tuples
            # tempout = []
            userid , movieid , rating , timestamp = data
            # tempout.append(userid)
            # tempout.append((movieid , float(rating)))
            # print tempout

            #
            print "{0},({1},{2})".format(userid , movieid , rating)

以下是打印声明:

def reducer():

    oldKey = None
    rating_arr = []

    for line in sys.stdin:
        # So we'll recieve user, (movie,rating)
        # We need to group the tuples for unique users
        # we'll append the tuples to an array
        # Given that we have two data points , we'll split the
        # data at only first occurance of ','
        # This splits the string only at first comma

        data = line.strip().split(',',1)
        # print len(data) , data
        # check for 2 data values
        if len(data) != 2:
            continue

        x , y = data

        if oldKey and oldKey != x:

            print "{0},{1}".format(oldKey , rating_arr)
            oldKey = x
            rating_arr = []
        oldKey = x
        rating_arr.append(y)
        # print rating_arr
    if oldKey != None:
        print "{0},{1}".format(oldKey , rating_arr)

输入为:671,(4973,4.5)\n671,(4993,5.0)\n670,(4995,4.0)` 输出为:

671,['(4973,4.5)', '(4993,5.0)']
670,['(4995,4.0)']

我需要元组,没有字符串。

b1payxdu

b1payxdu1#

事实上,数据是一个字符串,然后您分割和分配 y 对它来说,它仍然是一根弦。
如果您想要元组的原始值,作为数字,您需要解析它们。 ast.literal_eval 我可以帮忙。
例如,

In [1]: line = """671,(4973,4.5)"""

In [2]:  data = line.strip().split(',',1)

In [3]: data
Out[3]: ['671', '(4973,4.5)']

In [4]: x , y = data

In [5]: type(y)
Out[5]: str

In [6]: import ast

In [7]: y = ast.literal_eval(y)

In [8]: y
Out[8]: (4973, 4.5)

In [9]: type(y)
Out[9]: tuple

In [10]: type(y[0])
Out[10]: int

现在,如果您想切换到pyspark,那么您可以对变量/对象类型进行更多的控制,而不是对hadoop流的所有字符串进行控制

相关问题