Reputation: 19
1I know there are several posts about this on this website. However, my counter function does not work.
I have a CSV file with tweets about sports. I am trying to find the frequency of the following hashtags ["#lovepatriots", "#goJets", etc.] with a total of 10 hashtags.
Below is my code. I want to use the format of the code below instead of a counter function.
def readCSV():
myFile = open("/Users/acantrr/Desktop/south.csv", newline='', encoding='utf-8"')
fileString=myFile.read()
fileString = re.sub ('[^\s\w#]+',' ',fileString)
fileString = re.sub("\d+", "", fileString)
fileString = fileString.lower()
myFile.close()
myList= fileString.split()
return myList
def freqdic():
myList = readCSV()
for word in myList:
# Add a word to my dict. What should the val be?
if not word_freqs.has_key(word):
word_freqs[word] = 1
print('Saw', word, 'for the first time')
else:
word_freqs[word] = word_freqs[word]+1
print('Saw', word, 'again. Doh :(')
I am get the following error:
AttributeError: 'dict' object has no attribute 'has_key'
Upvotes: 1
Views: 223
Reputation: 45542
This error
AttributeError: 'dict' object has no attribute 'has_key'
tells me you are using Python 3.
From What's New in Python 3.0:
Removed.
dict.has_key()
– use thein
operator instead.
To fix your problem change
if not word_freqs.has_key(word):
to
if word not in word_freqs:
Better yet, use collections.Counter
and your function becomes:
def freqdic():
words = readCSV()
word_freqs = collections.Counter(words)
return word_freqs
or even
def freqdic():
return collections.Counter(readCSV())
Upvotes: 1