为什么我的函数在Python中返回空字符串?
我正在做的事情是,从一段文字中去掉所有的词性,除了名词。
为此我写了一个函数。可能这个代码并不是最好的或者最优化的,因为我刚开始学习用Python编程。我相信代码里一定有很基础的错误,但我就是找不到。
在我的函数里,有两个输入参数。一个是硬盘上文本的存放位置,另一个是我们想要输出结果的文件位置。
下面是代码。
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"
2 个回答
0
函数的最后一句话应该是 return
。
因为你用了 print data_out
,所以你返回的是 print
的返回值,而这个返回值是“无”(none)。
比如:
In []: def test():
..: print 'Hello!'
..:
In []: res = test()
Hello!
In []: res is None
Out[]: True
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