社区所有版块导航
Python
python开源   Django   Python   DjangoApp   pycharm  
DATA
docker   Elasticsearch  
aigc
aigc   chatgpt  
WEB开发
linux   MongoDB   Redis   DATABASE   NGINX   其他Web框架   web工具   zookeeper   tornado   NoSql   Bootstrap   js   peewee   Git   bottle   IE   MQ   Jquery  
机器学习
机器学习算法  
Python88.com
反馈   公告   社区推广  
产品
短视频  
印度
印度  
Py学习  »  Python

从一组文档中,如何在python for Mapreduce中计算单词、文档数和计数

learner • 4 年前 • 494 次点击  

我有两个文件,我需要计算两个文件中的单词数,以及每个单词的文件名。 doc1。txt=“我有一个苹果”,doc2。txt=“我住在公寓里”。 现在我想做MapReduce,输出如下: ((单词、文件名)、计数)。 示例:((apple,doc1.txt),1)

#!/usr/bin/env python

导入系统 导入glob #从字符串导入标点符号 #---从stdin获取所有线路--- 对于系统中的行。标准文本: #---删除前导和尾随空格--- #直线。翻译(无,标点符号)。带('\t') 直线。strip()

#--- split the line into words ---
words = line.split()
doc_name = glob.glob("*.txt")

for doc in doc_name:
    print(doc)
    if doc[] == '':
        
    for word in words:
        
        #word = word.rstrip()
        key = word+ ',' +doc 
        #print '%s\t%s' % (key, "1")

此代码每次都会打印每个文档中的所有单词,但对于这两个文档,它们会在每个单词中指定每个文档的名称,如下所示: (苹果,doc1.txt),1 (苹果,doc2.txt),1

Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/128265