该功能在Pycharm中运行,但是当导入Wing101时,该文件不会被读取

时间:2018-10-05 16:40:22

标签: python

所以我帮助编写了一个程序,该程序读取某个.txt文件并返回某些单词的计数。

制作完成后,它可以毫无问题地在Pycharm中运行;当我将其带入Wing101以使其成为函数时,无法读取该文件,并且出现此错误。

the input

你们能帮我弄清楚为什么不读取文件的原因吗?我将它与.txt文件放在同一文件夹中,并且都没有移动,所以我不知道为什么会收到此错误。

def analyzeSMS(fileName):
    file = open(fileName, "r")
    allowed_characters = " \tabcdefghijklmnopqrstuvwxyz-\'"

    lines = []

    ham_dictionary = {}
    spam_dictionary = {}

    ham_line_lengths = []

    # first read in the lines from the file, store each line as an element in the lines list
    for line in file:
        lines.append(''.join([char for char in line.lower() if char in allowed_characters]))

    # next go through each line and
    for line in lines:
        words_in_line = line.split()
        if words_in_line[0] == 'ham':
            ham_line_lengths.append(len(words_in_line) - 1)
            #add words to ham dictionary
            for index in range(1, len(words_in_line)):
                current_word = words_in_line[index]
                if current_word in ham_dictionary:
                    ham_dictionary[current_word] = ham_dictionary[current_word] + 1
                else:
                    ham_dictionary.update({current_word: 1})
        else:
            # add words to spam dictionary
            for index in range(1, len(words_in_line)):
                current_word = words_in_line[index]
                if current_word in spam_dictionary:
                    spam_dictionary[current_word] = spam_dictionary[current_word] + 1
                else:
                    spam_dictionary.update({current_word: 1})

    most_popular_ham = ''
    most_popular_ham_count = 0

    for key, value in ham_dictionary.items():
        if value > most_popular_ham_count:
            most_popular_ham_count = value
            most_popular_ham = key

    most_popular_spam = ''
    most_popular_spam_count = 0

    for key, value in spam_dictionary.items():
        if value > most_popular_spam_count:
            most_popular_spam_count = value
            most_popular_spam = key

    print("Most popular word in ham: " + str(most_popular_ham) + ' with ' + str(most_popular_ham_count) + ' occurences.')
    print("Most popular word in spam: " + str(most_popular_spam) + ' with ' + str(most_popular_spam_count) + ' occurences.')
    print(ham_line_lengths)

0 个答案:

没有答案