我正在做的是從文本中刪除除名詞以外的所有詞類。爲什麼我的函數在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"
可能的重複[如何提取名詞使用NLTK pos \ _tag()?](http://stackoverflow.com/questions/24409642/how-to-extract-nouns-using-nltk-pos-tag) – alvas
你試過我以前的代碼建議在http://stackoverflow.com/questions/24409642/how-to-extract-nouns-using-nltk-pos-tag – alvas
@alvas這是一個完全不同的問題。這就是爲什麼我沒有把它帶到那裏。而且我已經嘗試過你的建議,我會一旦想到這個基本的東西。我對我的功能中的錯誤非常好奇。你能幫我解決嗎? – user3710832