简体   繁体   中英

syntax errors on creating wordDictionary of word and occurences

Having Attribute error issue on line 32. Requesting some assistance figuring out how to display word and occurrences.

import re

file_object = open('dialog.txt')
# read the file content
fileContents = file_object.read()
# convert fileContents to lowercase
final_dialog = fileContents.lower()
# print(final_dialog)

# replace a-z and spaces with cleanText variable
a_string = final_dialog
cleanText = re.sub("[^0-9a-zA-Z]+", "1", a_string)
# print(cleanText)

# wordlist that contains all words found in cleanText
text_string = cleanText
wordList = re.sub("1"," ", text_string)
# print(wordList)

#wordDictionary to count occurrence of each word to list in wordList
wordDictionary = dict()
#loop through .txt
for line in list(wordList):
    # remove spaces and newline characters
    line = line.strip()

    # split the line into words
    words = line.split()

    #iterate over each word in line
    for word in words.split():
        if word not in wordDictionary:
            wordDictionary[word] = 1
        else:
            wordDictionary[word] += 1

        # print contents of dictionary
        print(word)




# print file content
# print(fileContents)
# close file
# file_object.close()

Having Attribute error issue on line 32. Requesting some assistance figuring out how to display word and occurrences.

I think the error is

for word in words.split():

and should be replaced with

for word in words:

Explanation: words is already a list. A list has no split method, so you'll get an AttributeError when trying to call that method.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM