如何修复以下代码中的错误:“NameError:global name'filtered\u text'is not defined”?

2021-11-29 23:08:32 发布

您现在位置:Python中文网/ 问答频道 /正文

import re

from sys import argv


def read_file(fname):
    """ open and extract the text from the file """
    txt_file = open(fname, 'r')
    txt = txt_file.read()
    txt_file.close()
    return txt


def clean_space(files):
    """ remove spaces from the file """
    return files.replace('\n', '')


def filter_file(files):
    """ remove punctuation and filter small words from the file """
    split_words = map(lambda x: re.sub('[^A-Za-z0-9]+', '', x),
                        files.split())
    filtered_txt = [x for x in split_words if len(x) > 1]
    return filtered_txt


def dict_count(files):
    """ for loop to return dict with word count and length keys """
    lengths = {}
    for word in filtered_text:  # And this also
        length = len(word)
        if length not in lengths:
            lengths[length] = 0
        lengths[length] += 1
    for length, counter in lengths.item():
        return "Words of length %d: %d" % (length, counter)


def print_result(fname):
    fi = dict_count(filter_file(clean_space(read_file(fname))))
    print fi


if __name__ == '__main__':

    script, fname = argv
    print_result(fname)