尝试编写递归计算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)


是我目前拥有的

最佳答案

我认为这可能对您有帮助:

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

关于python - 尝试编写递归计算Python中文本文件中单词出现次数的函数,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/43648376/

10-12 16:54