Hadoop的streamingAPI与MapReduce[Python]

1.创建模拟文本

1.1 机器模拟生成

from collections import namedtuple
from faker import Faker

# 初始化Faker
fake = Faker()

# 定义一个namedtuple类型,包含id, subject, text字段
GaokaoQuestion = namedtuple('GaokaoQuestion', 'id subject text')

# 定义生成模拟数据的函数
def generate_faker_data(num_samples):
    data = []
    for _ in range(num_samples):
        # 使用faker生成数据
        subject = fake.word()
        text = fake.sentence()
        
        # 使用md5生成id
        id_value = f"{text} {subject}"
        id_hash = hashlib.md5(id_value.encode('utf-8')).hexdigest()
        
        # 创建namedtuple实例
        question = GaokaoQuestion(id=id_hash, subject=subject, text=text)
        data.append(question)
    return data

# 生成3条模拟数据
samples = generate_faker_data(3)

# 打印生成的数据
for sample in samples:
    print(sample)

2.手动生成

cat > test_data.jsonl << EOF
{"id":"1", "subject":"Math", "text":"Math question"}
{"id":"2", "subject":"Science", "text":"Science question"}
{"id":"3", "subject":"Math", "text":"Another Math question"}
EOF

2. 使用mapperduce统计标签分布和抽取指定标签

#!/usr/bin/env python3
import sys
import json
from collections import defaultdict

# 指定需要抽取的subject标签列表
TARGET_SUBJECTS = ["数学", "物理"]

def mapper():
    for line in sys.stdin:
        data = json.loads(line)
        if data['subject'] in TARGET_SUBJECTS:
            print(json.dumps(data))


def reducer():
    counts = defaultdict(int)
    for line in sys.stdin:
        subject, count = line.strip().split('\t')
        counts[subject] += int(count)
    for subject, count in counts.items():
        print(f"{subject}\t{count}")

if __name__ == "__main__":
    if len(sys.argv) > 1 and sys.argv[1] == 'reduce':
        reducer()
    else:
        mapper()

3. 运行Map函数并排序结果以模拟Reduce任务:

cat test_data.jsonl | python3 mapper_reducer.py | sort -k1,1 | python3 mapper_reducer.py reduce

4.运行在无网络开发机上

# 假设input_data.jsonl是HDFS上的输入文件路径
# 假设output是HDFS上输出结果的路径

# 运行Map任务
hadoop fs -get /path/to/input_data.jsonl input_data.jsonl
python \Auser\tmp\mapper_reducer_script\mapper_reducer.py | sort -k1,1 > mapped_output.txt

# 运行Reduce任务
python \Auser\tmp\mapper_reducer_script\mapper_reducer.py reduce < mapped_output.txt > reduced_output.txt

# 将结果上传到HDFS
hadoop fs -put reduced_output.txt /path/to/output/
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
是的,在 Windows 系统下 Hadoop 中的 MapReduce 可以使用 Python 代码实现。具体来说,可以使用 PythonHadoop Streaming API,将 Python 脚本作为 mapper 和 reducer,然后使用 Hadoopstreaming 工具来运行 MapReduce 作业。使用 Hadoop Streaming API,你可以使用任何语言实现 mapper 和 reducer,只要这些程序能够从标准输入读取数据,并将结果写入标准输出。下面是一个使用 Python 实现的 MapReduce 作业的例子: 假设我们有一个文本文件,其中每行是一个整数,我们想要计算这些整数的和,可以使用以下两个 Python 脚本作为 mapper 和 reducer: mapper.py: ```python #!/usr/bin/env python import sys for line in sys.stdin: line = line.strip() if line: print(line + "\t" + line) reducer.py: #!/usr/bin/env python import sys total = 0 for line in sys.stdin: line = line.strip() if line: total += int(line.split("\t")[1]) print("Total:\t" + str(total)) ``` 然后,我们可以使用以下命令来运行 MapReduce 作业: ``` $ hadoop jar /path/to/hadoop-streaming.jar \ -file /path/to/mapper.py \ -mapper /path/to/mapper.py \ -file /path/to/reducer.py \ -reducer /path/to/reducer.py \ -input /path/to/input \ -output /path/to/output ``` 这里的 `/path/to/hadoop-streaming.jar` 是 Hadoop streaming 工具的路径,`/path/to/mapper.py` 和 `/path/to/reducer.py` 是我们刚才编写的 Python 脚本的路径,`/path/to/input` 和 `/path/to/output` 分别是输入和输出的路径。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值