提取所有包含介词“to”的句子在宾夕法尼亚树存储中

2024-05-16 14:10:54 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在用python做作业。我的想法是,我需要提取所有包含动词“给予”和介词“to”的句子(例如,我给女孩一束花束)。我已经想出了一个代码,它向我报告了错误的缩进空间错误。我不知道出什么事了。我写的代码如下:

import nltk

from nltk import treebank

for filename in nltk.corpus.treebank.fileids():

    files=open(filename,'r')

    file=files.read()

    for sentence in file:

        a=sentence.index('to')
        #a=the position in which 'to' appears

        b=sentence.index('give')
        #b=the position in which 'give' appears

        mylist=[]

        if a!=-1 and b!=-1:
                #if a and b exist simultaneously
                mylist.append(sentence)

                print(mylist)
                new_file_name='List'+'.txt'
                #create a new file

                file=open(new_file_name,'w')
                for sentence in file:
                    file.write(sentence)
                    file.write('\n')
                file.close()

有人能帮我吗?


Tags: to代码inimportnewfor错误files