【问题标题】:using a dictionary find the line number a word in a file appears on使用字典查找文件中出现的单词的行号
【发布时间】:2013-06-05 01:19:33
【问题描述】:

所以对于家庭作业,我必须找到一个或多个单词(由列表给出)出现的行号。到目前为止我有这个

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]))   

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

【问题讨论】:

  • 缩进你的代码。什么不起作用?
  • 几乎所有内容,我可以打开文件并将其放入列表中,但随后我需要获取字典,其中每个单词都是键,值是单词所在的行号
  • 1) 如果有人给你笔和纸,并告诉你解决问题的方式,他可以按照完全相同的步骤,总是想出完全相同的解决方案,你的解决方案是什么是? 2)它看起来像伪代码? 3) 作为 Python 源代码,它会是什么样子? 4) 实施和错误修复 3).
  • 试着给自己一个问题的输入和输出的例子。

标签: python file list dictionary


【解决方案1】:
def index(filename, wordlist):

    # Initialize some variable with meaningful names

    with open(filename) as infile:
        for line in infile:
            # Do something with the line

    return # something

这里还有一些提示可以让您的代码更整洁,但目前可能过于高级:enumeratedefaultdict(list)

【讨论】:

  • enumerate 也可能对 OP 有帮助 (+1)
【解决方案2】:

因为它的作业,我只会帮你一个算法

foreach line in the_file:
     if search_word in line:
        print line_number

这距离python只有一小步

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-03-27
    • 2013-02-11
    • 2011-02-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多