2012-09-01 36 views
-4

我有一個包含以下功能的模塊文件:Readlines()與Read() - 我可以在兩個函數之間來回轉換數據嗎?

def replace(filename): 
    match = re.sub(r'[^\s^\w]risk', 'risk', filename) 
    return match 

def count_words(newstring): 
    from collections import defaultdict 
    word_dict=defaultdict(int) 
    for line in newstring: 
     words=line.lower().split() 
     for word in words: 
      word_dict[word]+=1 

    for word in word_dict: 
     if'risk'==word: 
      return word, word_dict[word] 

我這樣做是在空閒時:

>>> mylist = open('C:\\Users\\ahn_133\\Desktop\\Python Project\\test10.txt').read() 
>>> newstrings=replace(mylist)  
>>> newone=count_words(newstrings) 

test10.txt只包含像測試的話:

風險風險較高的風險。風險?

我得到以下錯誤:

Traceback (most recent call last): 
    File "<pyshell#134>", line 1, in <module> 
    newPH = replace(newPassage) 
    File "C:\Users\ahn_133\Desktop\Python Project\text_modules.py", line 56, in replace 
    match = re.sub(r'[^\s^\w]risk', 'risk', filename) 
    File "C:\Python27\lib\re.py", line 151, in sub 
    return _compile(pattern, flags).sub(repl, string, count) 
TypeError: expected string or buffer 

反正是有,但不保存newstrings到一個文件中,使用readlines()打開它,然後運行count_words功能同時運行的功能呢?

+3

回溯說,當你寫發生錯誤'newPH =替換(newPassage)'。你能發佈你的實際代碼嗎? –

+3

另外:我想你可能想改變你的變量名稱。 'mylist'不是一個列表,'filename'不是一個文件名,'match'不是一個匹配對象,'newstrings'不是一個字符串集合,'newone'是一個二元組。就其本身而言,其中任何一個都不會那麼糟糕,但其中的一組有點令人困惑。 – DSM

+1

是的,我認爲這裏的問題是,你還不能確定你自己的變量是什麼類型的。 – jdi

回答

0

要運行模塊,您只需要執行python modulename.pypython.exe modulename.py - 或者只需雙擊該圖標即可。

但我猜你的問題真不是什麼你的問題標題狀態,讓您真正應該學習how to debug python

相關問題