2017-04-27 80 views
1

試圖編寫遞歸計算單詞在Python中出現在文本文件中的次數的函數。試圖編寫遞歸計算單詞在Python中的文本文件中出現的次數的函數

def word_count(filename, word): 
with open('C:/Users/Ibrahim/Desktop/file.txt', 'r') as f: 
    result_list = [x.split(',') for x in f.readlines()] 
    for i in result_list: 
     if i == word: 
      return word_count(filename,word) 

是我目前擁有的。

+0

使用計數器,一個內置的模塊... – Aditya

+0

你可以分享你的txt文件的預覽? – Aditya

+1

幾件事:1.每個遞歸函數都必須有終止條件。你沒有。你似乎沒有在任何地方保持單詞匹配的數量。 3.使用open(...)調用'wordcount'意味着,每次調用該函數時,都會有一個打開的文件描述符。 – yeniv

回答

0

Counter是你的朋友在這裏,即:

from collections import Counter 
f = open('yourfile.txt', 'r') 
counts = Counter(f.read().split()) 
print counts 

要檢查特定的單詞存在:

if "myword" in counts: 
    print "exists" 

爲了得到一個特定的詞計數值,使用:

print counts.get('myword') 
# or simply 
print counts['myword'] 

備註:

A Counter只是一個dict的子類,並支持所有的字典操作符和方法。

0

我認爲這可能對您有所幫助:

import sys, re 


def word_count(filename, niddle, splitter=","): 
    regex_pattern = '|'.join(map(re.escape, splitter)) 
    with open(filename, 'r') as f: 
     words = [ word for line in f.read().splitlines() for word in re.split(regex_pattern, line)] 

    words = filter(None, words) 
    print "Total Words :", len(words) 
    print "Searching %s in list" % niddle 
    print "Total Occurance : %d" % words.count(niddle) 


def main(argv): 
    splitter = "," 

    if len(argv)==3: 
     filename, word, splitter = argv 
    elif len(argv)==2: 
     filename, word = argv 
     splitter = splitter 
    else: 
     print "Usage : word_count.py <file> <word> <splitter>" 
     sys.exit() 

    word_count(filename, word, splitter) 


if __name__ == "__main__": 
    main(sys.argv[1:]) 
相關問題