【问题标题】:Python looping text file to find and printPython循环文本文件以查找和打印
【发布时间】:2019-01-29 09:29:27
【问题描述】:

此 Python 代码运行但打印文本文件的最后一页。不知道为什么,但我的目标是打印指定文本行下方的整行文本(包含特定字符串 ** Direct ** 的行)。如何遍历文本文件,在每一行中搜索指定的字符串,并在找到时打印其正下方的行?我搜索了许多在线论坛,但没有找到一个易于理解的示例。我使用 Python Sypder 2.7。任何帮助表示赞赏

import os
Path = '..\\Test.txt'

if os.path.isfile(Path): 
    with open(Path) as f:
        for line in f:
            print line
else:
    print Path, "doesn't exist"
f.close()

【问题讨论】:

  • 你在搜索什么字符串?
  • 请检查这个解决方案是否有帮助! - stackoverflow.com/questions/46410190/…
  • 字符串是指定字符串正下方的一行。该字符串是一个数字,并且该数字会随着文本文件的进行而变化,例如,第一个实例可能是 20,接下来是 30,接下来是 40 等等。但每个实例都位于指定字符串正下方的一行
  • @Nui 好吧,这听起来与下面发布的答案完全不同。要搜索的number string 落入下面的specified 字符串是什么?
  • @Nui 我已根据您在评论中的要求编辑了我的答案!

标签: python python-2.7


【解决方案1】:

Python 3.x:

dummy.txt

Mango
Anday Wala Burger
40
Aloo
Anday
Ghobi
Anday Wala Burger
30
Kheerey
Anday Wala Burger

py:

searchString = 'Anday Wala Burger'    
with open('dummy.txt', "r") as input:
    try:
        for line in input:
            if searchString in line:
                print(next(input), end='')
    except StopIteration:
            pass

输出:

40
30

编辑:

Python 2.7:

dummyFile= "dummy.txt"
searchString = 'Anday Wala Burger'

with open(dummyFile) as f:
    content = f.readlines()

# you may also want to remove empty lines
content = [l.strip() for l in content if l.strip()]

# flag
nextLine = False

for line in content:

    if searchString in line:
        nextLine = not nextLine
    else:
        if nextLine:
            print(line)
            nextLine = not nextLine
        else:
            pass

输出:

40
30

【讨论】:

【解决方案2】:

您需要进行一些更改:

1.-阅读台词

2.- 与您的文字进行比较

import os
Path = '..\\Test.txt'
look='**Direct**'

if os.path.isfile(Path): 
    with open(Path, "r") as f:
        for line in f:
            if look in line:
                print (line)
else:
    print (Path, "doesn't exist")

【讨论】:

  • 谢谢。这行得通,但我实际上需要指定外观文本正下方的行。我认为@Albin Paul 有“索引 +1”
【解决方案3】:

查看re 模块。它包括re.search() 函数,用于在字符串中搜索模式。

要打印下一行,您可以利用文件对象可迭代这一事实,使用f.next()

例如,你可以这样做:

import os
import re

Path = 'foo.txt'
Pattern = "spam"  # String to be searched

if os.path.isfile(Path): 
    with open(Path) as f:
        for line in f:
            if re.search(Pattern, line):
                print(f.next())
else:
    print(Path, "doesn't exist")

顺便说一句,你不需要最后的f.close()with 语句已经处理了它。

【讨论】:

    【解决方案4】:

    检查one是否在文件的任何行中,打印找到的下一行将是下一个lineno文件将设置为currentlineno+1

    临时文件的内容

    one
    two
    three
    four
    

    Python 文件

    with open('temp') as f:
       found=-1 
       #no lines are found to print so found is negative in value since line no in a file cannot be negative
       for index,line in enumerate(f):
            if found==index:
                print(line)
            if 'one' in line:
                found=index+1
                # when the condition is True found is set to the line no that we need to print  
    

    输出

    two
    

    【讨论】:

    • 工作得很好,保罗!
    • 保罗为什么首先定义了found=-1?并且 index 是一个内置的 Python 术语(因此不需要预先定义)?
    • @Nui 之所以定义是因为我检查了文件的索引或 lineno 是否等于 found 所以必须定义 found 以检查否则它显示分配之前引用的错误。
    • Python 中的索引似乎是通用的,并且从 0 开始。当您将它与枚举一起使用时,“索引”是枚举的“值”部分,对吗?您的代码以相同的方式运行而没有找到 =-1
    • @Albin Paul 您能否在 'found=-1' 中添加一些注释/cmets 并在相应的 if 行中找到行?
    猜你喜欢
    • 2016-07-27
    • 1970-01-01
    • 2016-02-08
    • 2018-12-30
    • 2021-06-17
    • 2014-06-16
    • 2013-10-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多