簡體   English   中英

搜索文件中的單詞並打印python中出現該單詞的行號

[英]search a word in a file and print the line number where that word occurs in python

如何使用函數在文本文件中找到單詞出現的行並打印相應的行號?

我不得不用段落打開一個文本文件,然后我應該在段落中搜索某些單詞,然后打印單詞的特定行號。

這是我到目前為止所擁有的。

def index (filepath, keywords):

    file = open(filepath)
    files_lines = [line for line in file]
    counter = 0
    for line in files_lines:
        counter += 1
        if line.find(keywords) >= 0:
            print(keywords, counter)
    counter = 0

這就是輸出的方式

    >>index('file.txt',['network', 'device', 'local'])

network    9

device     4

local      11

注意:網絡,設備和本地是我試圖在文件中搜索的單詞,而9,4,1是這些單詞出現的行號。

我收到一個錯誤,無法隱式地將列表轉換為str。 任何幫助將非常感激。 謝謝。

if line.find(keywords) >= 0: 

是錯的。 你需要找出keywords任何元素是否包含line 像這樣

if any(line.find(kw) > 0 for kw in keywords):

線路,行

files_lines = [line for line in file]
counter = 0

不是非常pythonic,更像這樣:

def index (filepath, keywords):
    with open(filepath) as f:
        for counter, line in enumerate(f, start = 1):
            if line.find(keywords) >= 0:
               print(keywords, counter)

致謝 :感謝Lukas Graf向我展示了必須在enumerate設置start參數

你得到錯誤

TypeError: Can't convert 'list' object to str implicitly

因為你使用line.find(keywords)將一個列表( keywords )傳遞給find() ,它需要一個字符串。

您需要使用循環單獨搜索每個關鍵字:

def index(filepath, keywords):
    with open(filepath) as f:
        for lineno, line in enumerate(f, start=1):
            matches = [k for k in keywords if k in line]
            if matches:
                result = "{:<15} {}".format(','.join(matches), lineno)
                print(result)


index('file.txt', ['network', 'device', 'local'])

在這里,我還使用了enumerate()來簡化行計數和字符串格式化 ,使輸出示例中的輸出一致 表達式matches = [k for k in keywords if k in line]是一個列表解析 ,它構建了作為line的子串的所有關鍵字的列表。

示例輸出:

network,device  1
network         2
device          3
local           4
device,local    5

如果你得到的錯誤cannot convert list to str implicity則意味着你已經編寫了一個適用於字符串的參數,但不適用於列表。

解決此錯誤的一種方法:

variable = [1, 2, 3, 4, 5]

variable = str(variable)
# NOW ARGUMENT
variable = list(variable) # change it back

我不確定這是否對你有所幫助,但是其他人已經回答了你的問題,而我只是為了額外的知識而輸入,如果你還不知道你知道的話!

暫無
暫無

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

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