尝试编写递归计算单词出现在Python文本文件中的次数的函数

时间:2017-04-27 03:55:14

标签: python

尝试编写函数,以递归方式计算word在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)

是我现在拥有的。

2 个答案:

答案 0 :(得分:1)

我认为它可能对您有所帮助:

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:])

答案 1 :(得分: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']

注意:

Counter只是一个dict子类,支持所有dict运算符和方法。