将城市和温度值放入变量中以在 reducer 文件中使用

get city and temperature values into variables to use in reducer file

我正在尝试开发一个 mapreduce 程序以从文本文件中显示城市的最高温度。

我的 Temperatures.txt 文件格式如下:

城市1 10

城市 2 12

...

而且我已经有了像这样工作的 mapper.py 文件:

import sys

for line in sys.stdin:
    line = line.strip()
    print line  

但我不只是做 print line,我想做这样的事情:

print '%s\t%s' % (city ,temperature)

因为要开发 reducer.py 文件我需要这个,所以我的问题是你是否知道我如何在我的 mapper.py 文件中获取每一行并将城市名称放入我的变量中我的可变温度中的城市和温度,如下所示:

import sys

for line in sys.stdin:

    line = line.strip()
    words = line.split()
    for word in words:
        city = # how can i get this?
        temperature = # how can i get this?
    print line
    # so i can show the resut like this
    print '%s\t%s' % (city ,temperature)

您可以使用以下代码

import sys
for line in sys.stdin:
    words = line.split()
    if len(words) < 2:
        continue;
    city = words[:-1]
    city = ''.join(city)
    temperature = words[-1]
    print line
    # so i can show the resut like this
    print '%s\t%s' % (city ,temperature)

如果城市和温度在每一行中,您需要从以下行中获取它们:

import sys

for line in sys.stdin:
    city, temperature = line.rsplit(None, 1)
    print '%s\t%s' % (city ,temperature)

您还应该使用 rsplit,并且对于名称中包含多个单词的城市只拆分一次。

如果文件中有空行,您还需要捕获这些空行:

for line in sys.stdin:
    if line.strip():
        city, temperature = line.rsplit(None, 1)
        print '%s\t%s' % (city ,temperature)

或使用 try/except:

import sys

for line in sys.stdin:
    try:
        city, temperature = line.rsplit(None, 1)
        print '%s\t%s' % (city ,temperature)
    except ValueError:
        continue