簡體   English   中英

在不導入任何內容的情況下,在python 3中為列表中的每個單詞打印文本文件的行號

[英]Print the line number of a text file for each word from a list in python 3 without importing anything

我正在嘗試編寫一個函數index(),該函數將文本文件的名稱和單詞列表作為輸入。 對於列表中的每個單詞,該函數將在文本文件中找到單詞所在的行,並打印相應的行號(編號從1開始)。

例:

index('sawyer.txt',['hello','cloud','cherry','tree'])  

hello 824,965
cloud 583, 16403
cherry 345, 561, 7891
tree 11, 45, 651

我已經有計算文本文件中行總數的函數。 但是我將如何為列表中的每個單詞打印每個行號?

def file_len():
with open('sawyer.txt') as f:
    for i, l in enumerate(f):
        pass
return i + 1

任何幫助將不勝感激。

您可以使用以下代碼來做到這一點

>>> dict={}
>>> with open('sawyer.txt') as f:
...     for i, l in enumerate(f):
...             for word in l.strip().split(" "):
...                     if word in dict.keys():dict[word].append(i)
...                     else:dict[word]=[i]
...
>>> dict

您的案例的完整功能如下:

def word_locator(file, list_of_words):
    dict={}
    with open(file) as f:
        for i, l in enumerate(f):
            for word in l.split(" "):
                if word in list_of_words:
                    if word in dict.keys():dict[word].append(i)
                    else:dict[word]=[i]
    return dict


word_location_dictionary = word_locator('sawyer.txt', ['hello','cloud','cherry','tree'])

for k, v in word_location_dictionary.items():
    lines = map(str, v)
    print k + " " + ' '.join(lines)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM