【问题标题】:Get line numbers of words present in a file获取文件中存在的单词的行号
【发布时间】:2015-11-11 00:45:18
【问题描述】:

我有两个文件:

文件 1:

military  troop deployment number need  

文件 2:

foreign 1242
military 23020
firing  03848
troop 2939
number 0032
dog 1234
cat 12030
need w1212

我想从文件 1 中读取该行并打印这些单词以及它们在文件 2 中的行号。

我的输出应该是这样的:

military 2, troop 4, deployment <does not exist>, number 5, need 8

我试过代码:

words= 'military  troop  deployment  number  need'
sent = words.split()
print sent

with open("file2","r") as f1:
    for line_num,line in enumerate(f1):
        if any([word in line for word in sent]):
             print line_num, line

这是打印这些单词所在的所有行。除此之外,它还打印诸如 pre-military、necessively 等字词。我只需要那些确切的字词和它们的行号。请帮忙

【问题讨论】:

    标签: python file python-2.7 numbers line


    【解决方案1】:

    你打印错了。您想打印单词而不是整行。另外如果你使用any,你不知道匹配的是哪个词。

    这里有两种方法。第一个不检测空条目。

    words= 'military  troop  deployment  number  need'
    sent = words.split()
    
    matched = []
    with open("file2","r") as f1:
        for i, line in enumerate(f1):
            for word in sent:
                if word in line:
                    matched.append('%s %d' % (word, i + 1))
    
    print ', '.join(matched)
    

    输出:

    military 2, troop 4, number 5, need 8
    

    如果您也想打印空条目。

    words= 'military  troop  deployment  number  need'
    sent = words.split()
    
    linenos = {}
    
    with open("file2","r") as f1:
        for i, line in enumerate(f1):
            for word in sent:
                if word in line:
                    linenos[word] = i + 1
    
    matched2 = []
    for word in sent:
        if word in linenos:
            matched2.append('%s %d' % (word, linenos[word]))
        else:
            matched2.append('%s <does not exist>' % word)
    print ', '.join(matched2)
    

    输出:

    military 2, troop 4, deployment <does not exist>, number 5, need 8
    

    处理一个单词的多次出现并只打印第一行。

    words= 'military  troop  deployment  number  need'
    sent = words.split()
    linenos = {}
    
    with open("file2", "r") as f1:
        for i, line in enumerate(f1):
            for word in sent:
                if word in line:
                    if word in linenos:
                        linenos[word].append(i + 1)
                    else:
                        linenos[word] = [i + 1]
    
    matched2 = []
    for word in sent:
        if word in linenos:
            matched2.append('%s %r' % (word, linenos[word][0]))
        else:
            matched2.append('%s <does not exist>' % word)
    
    print ', '.join(matched2)
    

    输出与上一个示例相同。

    【讨论】:

    • 帮助很大。非常感谢 :) 而且,如果我只想让它打印最早的行号怎么办。就像军事发生在 10 个地方一样。如果我只想要第一名的行号怎么办?
    • 也许 dict 可以保存一个单词出现的所有行号的列表。然后,如果您只想要第一个,则只需使用列表的第 0 个元素。
    • 好的。我会尝试。如果可能的话,如果你也可以添加那行代码,那就太好了。我只是在学习。不过没有压力:)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-09-16
    • 2023-01-27
    • 2017-04-04
    • 1970-01-01
    • 2014-06-28
    相关资源
    最近更新 更多