【问题标题】:Searching a file搜索文件
【发布时间】:2009-12-18 09:48:56
【问题描述】:

这是参考我昨天发布的一个问题Searching a file in 3 different ways

我现在只需要在两件事上提供帮助,搜索文件并打印找到搜索结果的行以及该行之后到文件末尾的所有行。

最后,如果我搜索文件并打印找到搜索结果的行以及搜索结果之前和之后的多行,我需要编码方面的帮助。搜索结果前后打印的行数由用户定义,前后行数相同。

【问题讨论】:

  • 请发布您此时拥有的代码。

标签: python file search


【解决方案1】:

第一部分

for line in open("file"):
    line=line.rstrip()
    if "search" in line:
        f=1
    if f: print line

第二部分

context=3
search="myword"
f=open("file")
d={}
for n,line in enumerate(f):
    d[n%context]=line.rstrip()
    if search in line:
        for i in range(n+1,n+1+context):
            print d[i%context]
        for i in range(1,context):
            print f.next().rstrip()
f.close()

【讨论】:

  • 我喜欢。这比我想使用双端队列的要容易。如果匹配位于文件的前几行(n
猜你喜欢
  • 1970-01-01
  • 2023-03-28
  • 2010-11-07
  • 2021-03-10
  • 2018-05-08
  • 2011-04-16
  • 2022-01-15
相关资源
最近更新 更多