【问题标题】:Python - Find line number from text file [closed]Python - 从文本文件中查找行号[关闭]
【发布时间】:2017-01-02 16:05:27
【问题描述】:

我正在编写查看文本文件的代码,并查看输入是否在其中。

例如,

我输入“披萨”

我的文本文件包含:

bread
pizza
pasta
tomato

有没有办法打印披萨所在的行号?

【问题讨论】:

  • 开始阅读 Tutorial 并练习示例,很快您就会开始获得一些想法 - 在 shell 中尝试其中一些,找出哪些有效,哪些无效,查看built-in functions 的文档,看看是否有任何可以帮助您解决问题的文档。

标签: python numbers line


【解决方案1】:
with open('test.txt') as f:
    content = f.readlines()

index = [x for x in range(len(content)) if 'pizza' in content[x].lower()]

代码的第 (1) 部分将每一行读取为变量“content”中的单独列表。

仅当“pizza”存在于该行中时,第 (2) 部分才会填充第 # 行内容。 [x for x in range(len(content))] 只是填充所有索引值,而 'if 'pizza' in content[x].lower()' 保留与字符串匹配的行 #。

【讨论】:

  • 你能解释一下吗?
  • 对不起,我已经添加了解释
  • 然后我打印什么来给我行号?行号是什么变量?
  • index 包含行号列表。打印(索引)
  • 谢谢 :) 真的很有帮助
【解决方案2】:

有两种方法可以做到这一点:

  1. 将整个文件存储在内存中,以便您只读取一次
  2. 在每次搜索时通读文件,但不必存储它

对于方法一,先读入每一行,然后获取单词所在的索引:

with open('path.txt') as f: data = f.readlines()
line_no = data.index("pizza")

或者,通过文件查找索引:

with open('path.txt') as f:
    for line_no, line in enumerate(f):
        if line == "pizza":
            break
    else: # for loop ended => line not found
        line_no = -1

【讨论】:

    【解决方案3】:

    类似这样的:

    import re
    import os # You can go without is if you have other means to get your filepath
    
    i = 1
    matches = []
    target = raw_input("Please type string to match\n")
    with open(os.getenv("SOME_PATH") + "/myfile.txt") as fic: # open("myfile.txt") if in your current directory
         for line in fic:
             if re.search(target, line):
                 print "Found at line {}".format(i)
                 matches.append(i)
             i = i +1
    if not len(matches):
        raise Exception, "target not found"
    

    通过这样做,您可以输入一个正则表达式,它应该可以工作(即,如果您输入“p.zza”或“^p.*”,它就会工作。)。列表matches 将包含与输入模式匹配的所有行索引。

    【讨论】:

      【解决方案4】:
      print next (i for i,v in enumerate (open (fname),1) if v == needle)
      

      【讨论】:

      • 以后不想关闭文件?
      猜你喜欢
      • 1970-01-01
      • 2014-11-11
      • 1970-01-01
      • 2018-03-28
      • 2019-02-18
      • 2012-03-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多