我试图让StanfordDependencies模块工作,但是当我尝试从文本中解析树导致来自SubprocessBackend.py文件的WinError 32通知时,代码中似乎出现了错误。以下是尝试使用该模块的代码:
import StanfordDependencies
sd = StanfordDependencies.get_instance(backend='subprocess')
sent = sd.convert_tree('(S1 (NP (DT some) (JJ blue) (NN moose)))')
以下是调试的内容:
File "C:\Python34\lib\site-packages\StanfordDependencies\SubprocessBackend.py", line 111, in convert_tree
return self.convert_trees([ptb_tree], **kwargs)[0]
File "C:\Python34\lib\site-packages\StanfordDependencies\SubprocessBackend.py", line 87, in convert_trees
os.remove(input_file.name)
PermissionError: [WinError 32] The process cannot access the file because it is being used by another process: 'C:\\Users\\new\\AppData\\Local\\Temp\\tmpldetf3e5'
在此之后,我发布了出现问题的模块中包含的SubprocessBackend文件中的代码(最后一行是第87行):
self._raise_on_bad_representation(representation)
input_file = tempfile.NamedTemporaryFile(delete=False)
try:
for ptb_tree in ptb_trees:
self._raise_on_bad_input(ptb_tree)
tree_with_line_break = ptb_tree + "\n"
input_file.write(tree_with_line_break.encode("utf-8"))
input_file.flush()
command = [self.java_command,
'-ea',
'-cp', self.jar_filename,
JAVA_CLASS_NAME,
'-' + representation,
'-treeFile', input_file.name]
# if we're including erased, we want to include punctuation
# since otherwise we won't know what SD considers punctuation
if include_punct or include_erased:
command.append('-keepPunct')
if not universal:
command.append('-originalDependencies')
if debug:
print('Command:', ' '.join(command))
sd_process = subprocess.Popen(command, stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
universal_newlines=True)
return_code = sd_process.wait()
stderr = sd_process.stderr.read()
stdout = sd_process.stdout.read()
if debug:
print("stdout: {%s}" % stdout)
print("stderr: {%s}" % stderr)
print('Exit code:', return_code)
self._raise_on_bad_exit_or_output(return_code, stderr)
finally:
os.remove(input_file.name)
我是否应该在最后一个关闭文件的命令之前添加一些代码,或者是否有更好的方法?