我试图开发一个mapreduce程序来显示文本文件中城市的最高温度。
我的温度.txt文件具有以下格式:
城市1 10
城市 2 12
。
我已经有 mapper.py 文件像这样工作:
import sys
for line in sys.stdin:
line = line.strip()
print line
但不仅仅是做print line
,我想做这样的事情:
print '%st%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 '%st%s' % (city ,temperature)
如果城市和临时在每行中,您需要从该行中获取它们:
import sys
for line in sys.stdin:
city, temperature = line.rsplit(None, 1)
print '%st%s' % (city ,temperature)
您还应该使用rsplit
并且只对名称中包含多个单词的城市进行一次拆分。
如果文件中有空行,您还需要捕获这些行:
for line in sys.stdin:
if line.strip():
city, temperature = line.rsplit(None, 1)
print '%st%s' % (city ,temperature)
或使用尝试/例外:
import sys
for line in sys.stdin:
try:
city, temperature = line.rsplit(None, 1)
print '%st%s' % (city ,temperature)
except ValueError:
continue
您可以使用以下代码
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 '%st%s' % (city ,temperature)