2014-06-25 116 views
-1

我正在做的是從文本中刪除除名詞以外的所有詞類。爲什麼我的函數在python中返回空字符串?

我已經寫了一個函數。它可能不是最好的或優化的代碼,因爲我剛剛開始使用python進行編碼。我相信這個bug一定是非常基本的,但我無法弄清楚。

在我的函數中有兩個輸入作爲參數。一個是硬盤上文本的位置,另一個是我們想要輸出的文件的位置。

以下是驗證碼。

def extract_nouns(i_location, o_location): 
    import nltk 

    with open(i_location, "r") as myfile: 
     data = myfile.read().replace('\n', '')   

    tokens = nltk.word_tokenize(data) 
    tagged = nltk.pos_tag(tokens) 
    length = len(tagged) 
    a = list() 

    for i in range(0,length): 
     print(i) 
     log = (tagged[i][1][0] == 'N') 
     if log == False: 
      a.append(tagged[i][0]) 

    fin = open(i_location, 'r') 
    fout = open(o_location, "w+") 

    for line in fin: 
     for word in a: 
      line = line.replace(word, "") 
     fout.write(line) 

    with open(o_location, "r") as myfile_new: 
     data_out = myfile_new.read().replace('\n', '') 

    return data_out 

當我調用這個函數時它工作得很好。我得到了硬盤上的輸出,但是它並沒有返回接口上的輸出,或者我應該說,它返回一個空字符串而不是實際的輸出字符串。

這就是我所說的。

t = extract_nouns("input.txt","output.txt") 

如果您想嘗試,採取以下爲輸入文件的內容

"At eight o'clock on 
Thursday film morning word line test 
best beautiful Ram Aaron design" 

這是我在輸出文件中獲取的輸出(output.txt中)當我打電話功能,但函數返回接口上的空白字符串。它甚至不打印輸出。

"  
Thursday film morning word line test 
    Ram Aar design" 
+0

可能的重複[如何提取名詞使用NLTK pos \ _tag()?](http://stackoverflow.com/questions/24409642/how-to-extract-nouns-using-nltk-pos-tag) – alvas

+0

你試過我以前的代碼建議在http://stackoverflow.com/questions/24409642/how-to-extract-nouns-using-nltk-pos-tag – alvas

+0

@alvas這是一個完全不同的問題。這就是爲什麼我沒有把它帶到那裏。而且我已經嘗試過你的建議,我會一旦想到這個基本的東西。我對我的功能中的錯誤非常好奇。你能幫我解決嗎? – user3710832

回答

1

您需要關閉該文件第一:

for line in fin: 
    for word in a: 
     line = line.replace(word, "") 
      fout.write(line) 
fout.close() 

使用with通常是打開文件,它會自動關閉它們的最佳方式,並file.seek()回去了文件開始讀取:

def extract_nouns(i_location, o_location): 
    import nltk 

    with open(i_location, "r") as myfile: 
     data = myfile.read().replace('\n', '') 

    tokens = nltk.word_tokenize(data) 
    tagged = nltk.pos_tag(tokens) 
    length = len(tagged) 
    a = [] 

    for i in range(0,length): 
     print(i) 
     log = (tagged[i][1][0] == 'N') 
     if not log: 
      a.append(tagged[i][0]) 
    with open(i_location, 'r') as fin, open(o_location, "w+") as fout: 
     for line in fin: 
      for word in a: 
       line = line.replace(word, "") 
      fout.write(line) 
      fout.seek(0) # go back to start of file 
      data_out = fout.read().replace('\n' , '') 
     return data_out 
+0

耶穌!我不會想到它!非常感謝Padraic。我瘋狂地解決了這個錯誤。非常感謝! – user3710832

+0

不用擔心,我使用seek和with來打開所有文件。如果使用'with'忘記關閉文件將不再是問題! –

0

函數中的最後一條語句應該是return

因爲有print data_out,所以返回值爲print的返回值是none。

如:

In []: def test(): 
    ..:  print 'Hello!' 
    ..: 

In []: res = test() 
Hello! 

In []: res is None 
Out[]: True 
+0

即使我刪除'print data_out'!仍然不起作用! – user3710832

+0

你正在使用哪個版本的python?什麼是錯誤追溯? – alvas

相關問題