【问题标题】:search a word in a file and print the line number where that word occurs in python在文件中搜索一个单词并打印该单词在 python 中出现的行号
【发布时间】:2014-09-14 19:22:06
【问题描述】:

如何让你的函数在文本文件中找到单词出现的行并打印相应的行号?

我必须打开一个包含该段落的文本文件,然后应该在该段落中搜索某些单词,然后打印这些单词的特定行号。

这是我目前所拥有的。

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、11 是这些词出现的行号。

我收到一个错误,无法将 list 隐式转换为 str。任何帮助将非常感激。谢谢。

【问题讨论】:

  • 问题如何定义一个词?
  • 如果一个单词出现在多行怎么办?如果多个关键字出现在同一行怎么办?

标签: python line-numbers


【解决方案1】:
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 参数

【讨论】:

【解决方案2】:

你得到错误

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() 来简化行计数,并使用string formatting 使输出aligned 与您的示例一样。表达式matches = [k for k in keywords if k in line] 是一个list comprehension,它构建了一个包含line 子字符串的所有关键字的列表。

示例输出:

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

【讨论】:

    【解决方案3】:

    如果您收到错误cannot convert list to str implicity,则表示您编写的参数适用于字符串,但不适用于列表。

    解决此错误的一种方法:

    variable = [1, 2, 3, 4, 5]
    
    variable = str(variable)
    # NOW ARGUMENT
    variable = list(variable) # change it back
    

    我不确定这是否对您有所帮助,但其他人已经回答了您的问题,而我的输入只是为了获得额外的知识,如果您还不知道的话就知道了!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-02-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-09-09
      • 1970-01-01
      • 2018-12-20
      • 1970-01-01
      相关资源
      最近更新 更多