2016-12-01 37 views
0

我在我的readfiles.py中創建並填充了一個字典?現在我需要調用此Dict用於For循環中的另一個方法,以查看是否可以將來自另一個名爲CategoryGA的列表中的單詞與句子中的單詞相匹配。填充字典中的Cleanse變量:Python在另一種方法中調用全局字典

我的字典已填充兩個人之間的交談,這是從字典輸出的一段:

{0: ['hi'], 1: ['32 m fresno'], 2: ['u?'], 3: ['"33/f/ca', ' how r u?"'], 4: ['got a cam?']} 

該字典的鍵值是LINENUM和可變淨化是聊天。

readfiles.py

import re 
import os 

Chatfile = 'ChatLogs/#######/Chat1.txt' 
Lexfile = 'Lexicons/########.txt' 
cleanChat = dict() 

def ReadChat(): 

    with open(Chatfile) as file_read: 
     chat_content = file_read.readlines() 
     for linenum, line in enumerate(chat_content): 
      Regex = re.sub('<.*?>[^\S\r\n]', '', line) 
      #cleanChat = Cleanse 
      #print(linenum, cleanChat) 
      Cleanse = Regex.rstrip("\n").split(",") 

      cleanChat[linenum] = Cleanse 

    file_read.close() 

ReadChat() 

main.py

from collections import Counter 

from Categories.GainingAccess import GA 
from Readfiles import * 



CategoryGA = GA 
Hits = [] 
cleansedLex = [] 



    def SpeechActCounter(): 
     for line in cleanChat.values(): 
     for section in line: 
      if any(word in section for word in CategoryGA): 
       print(section) 
       #if any(word in line for word in CategoryGA): 
       print(line) 
       Word_Hit = False 
       for word in CategoryGA: 
        if line.find(word) != -1: 
         Word_Hit = True 
         Hits.append(word) 
         print('%s appeared on Line %s' % (word)) 

    count = Counter(Hits) 
    count.keys() 
    for key, value in count.items(): 
     print(key, ':', value) 
    SpeechActCounter() 

這是我的錯誤:

Traceback (most recent call last): 
    File "C:/Users/Lewis Collins/Desktop/Test/main.py", line 32, in <module> 
    SpeechActCounter() 
    File "C:/Users/Lewis Collins/Desktop/Test/main.py", line 22, in SpeechActCounter 
    if line.find(word) != -1: 
AttributeError: 'list' object has no attribute 'find' 

Process finished with exit code 1 

輸出:

['hi asl?'] 

我收到有限的輸出,並且for循環似乎被破壞,因爲它不會嘗試匹配if語句中的單詞,並且底部的print語句沒有達到。

內容我CategoryGA的:

import re 

GA = ["face", "cam", "donkey"] 
+0

GA正從另一個頁面拉入,我將發佈其中的內容 –

+0

您沒有行。你有*整數鍵*。在cleanChat中爲'line'生成字典的鍵。因此'字符串'試圖在這裏測試一個整數。 'in'期望右邊的操作數是可迭代的。 –

回答

0

你在字典迭代這裏:

for line in cleanChat: 

你的鑰匙是整數(行),而不是字符串或列表,所以word in line測試抱怨,因爲右邊的操作數line不是一個可迭代的對象(整數不是容器,它們不包含在其他對象中,因此測試成員資格是沒有意義的)。

如果你想在循環遍歷,明確地這樣做:

for line in cleanChat.values(): 

這樣line被設置爲在字典中的列表之一,每個Regex.rstrip("\n").split(",")操作的結果。

+0

啊我明白你的意思,所以我會說我的循環爲「在cleanChat.Cleanse()中的行:」 –

+0

@ L.C:不,作爲'cleanChat.values()'中的行。 –

+0

♦對,我明白你的意思,這是一個很好的解釋謝謝。我已經更正了我的代碼,但是現在當我運行它時,我沒有收到像我的代碼一樣的輸出,甚至沒有在主打印中確認此打印語句('%s出現在行%s'%(word)) –