2015-12-01 58 views
1

1我知道在这个网站上有几个关于此的帖子。但是,我的计数器功能不起作用。如何查找字典中的单词频率(CSV文件)

我有一个关于运动的推文的CSV文件。我试图通过总共10个哈希标签来查找以下主题标签[“#lovepatriots”,“#goJets”等)的频率。

以下是我的代码。我想使用下面的代码格式而不是计数器函数。

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 :(') 

我得到以下错误:

AttributeError: 'dict' object has no attribute 'has_key'  

CSV file image

+0

您能否显示您的csv文件的前几行看起来像什么? –

+1

那么现有代码有什么问题?你会得到例外还是坏结果? “不起作用”是什么意思? – skrrgwasme

+0

当我在交互部分输入print(freqDict())时,我不断收到以下错误:AttributeError:'dict'对象没有属性'has_key' – MarlaC

回答

1

此错误

AttributeError: 'dict' object has no attribute 'has_key' 

告诉我,你是使用Python 3

What's New in Python 3.0

Removed. dict.has_key() – use the in operator instead.

解决您的问题变化

if not word_freqs.has_key(word): 

if word not in word_freqs: 

更重要的是,使用collections.Counter和你的函数变为:

def freqdic(): 
    words = readCSV() 
    word_freqs = collections.Counter(words) 
    return word_freqs 

甚至

def freqdic(): 
    return collections.Counter(readCSV()) 
+0

谢谢史蒂芬。这非常有帮助,并帮助我找出其他一些事情! – MarlaC