【问题标题】:Python: read the content of a text file and look for a match/conditionPython:读取文本文件的内容并查找匹配/条件
【发布时间】:2012-06-27 20:04:10
【问题描述】:

我正在尝试打开一个文本文件并查找字符串Num_row_lables。如果Num_row_labels 的值大于等于10,则打印文件名。

在下面的示例中,我的文本文件 test.mrk 包含以下格式的一些文本:P.s.,我的文本文件没有 Num_row_labels >= 10。它总是有“equal to”。

Format= { Window_Type="Tabular", Tabular= { Num_row_labels=10 } }

所以我创建了一个变量teststring 来保存我将要查看的模式。 然后我打开了文件。

然后使用re,我在名为match 的变量中得到Num_row_labels=10。 在匹配时使用group(),我提取了我想要的阈值并使用int() 转换了string to int

如果文本文件的 Num_row_labels = 10 或任何大于 10 的 #,我的目的是将文本文件读取到 find/print Num_row_labels 的值以及文件名。

这是我的测试代码:

import os
import os.path
import re

teststring = """Format= { Window_Type="Tabular", Tabular= { Num_row_labels=10 } }"""
fname = "E:\MyUsers\ssbc\test.mrk"
fo = open(fname, "r")
match = re.search('Num_row_labels=(\d+)', teststring)
tnum = int(match.group(1))


if(tnum>=10):
        print(fname) 

如何确保在打开文件的内容中搜索匹配项并检查 tnum>=10 的条件?我的测试代码只会根据最后 4 行简单地打印文件名。我想确保搜索遍及我的文本文件的内容。

【问题讨论】:

    标签: python python-3.x python-2.7


    【解决方案1】:

    所以你要做的就是把整个文件作为一个字符串读出,然后在那个字符串上搜索你的模式

    with open(fname, "r") as fo:
        content_as_string = fo.read()
        match = re.search('Num_row_labels=(\d+)', content_as_string)
        # do want you want to the matchings
    

    【讨论】:

      【解决方案2】:

      根据条件读取文件内容的 Python 代码

          file = '../input/testtxt/kaggle.txt'
          output = []
          with open(file, 'r') as fp:
              lines = fp.readlines()
              for i in lines:
                  if('Image for' in i):
                      output.append(i)
                  
          print(output)
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2015-12-22
        • 2021-05-05
        • 2016-10-14
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-11-11
        • 1970-01-01
        相关资源
        最近更新 更多