使用字典找到文件中出现单词的行号

因此,对于家庭作业,我必须找到出现在单词上的行号(由列表给出)。到目前为止,我有这个


def index(f,l):

   'str,list(str)==nonetype'

    infile=open(f)

    file=infile.read()

    b=file.split('\n')

    G=file.splitlines()

    infile.close

    count=1

    res=0

    c={}

    a=[]

    for i in b:

        a+=[i]

    for n in l:

        while res <len(G):

            small={G[res]:count}

            c.update(small)

            count+=1

            res+=1

            if (a[res] in c) and (n in a[res]):

                print (n+'{}'.format(c[count]))   

所以我到达这里,因为它超出了范围,所以我得到了错误。我一直在努力,因为这一切现在看起来像胡言乱语。


慕田峪7331174
浏览 179回答 2
2回答

小唯快跑啊

def index(filename, wordlist):&nbsp; &nbsp; # Initialize some variable with meaningful names&nbsp; &nbsp; with open(filename) as infile:&nbsp; &nbsp; &nbsp; &nbsp; for line in infile:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; # Do something with the line&nbsp; &nbsp; return # something这里有一些更多的提示,可以让你的代码更简洁,但可能过于超前现在:enumerate,defaultdict(list)
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python