2014-06-25 117 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

相关问题