【问题标题】:Search txt file for varying keyword - then assign to variable在 txt 文件中搜索不同的关键字 - 然后分配给变量
【发布时间】:2016-09-04 19:37:22
【问题描述】:

我需要在 txt 文件中搜索格式为“i-0xxxyyyzzzz”的关键字 - 其中 xyz 是不同的字母数字字符。 然后我想分配分配的每个匹配项。目前我可以做到:

  f = open("file.txt", "r")
searchlines = f.readlines()
f.close()
for i, line in enumerate(searchlines):
    if "i-0" in line:
        for l in searchlines[i:i+1]: print l,
        print

但是,这会打印整行,而不仅仅是关键字。

【问题讨论】:

  • 您能否向我们展示一个示例输入文件以及您的确切期望?
  • @Kasramvd 不,当前版本将打印 2 ...
  • 基本上我在一个 JSON 文件中搜索随机分配的服务器卷名。然后我想将这些“i-0...”格式名称分配给一个变量,以便我可以针对它们运行任务。

标签: python file search keyword


【解决方案1】:

我建议使用正则表达式:

import re

token_regex = re.compile('i\-0[0-9a-z]*')
for line in open('file.txt'): // Note: 'r' is the default
   // You might find the token several times in the line
   matches = token_regex.findall(line)
   if matches:
     print '\n'.join(matches)

我不清楚你想用火柴做什么。我的示例将每行打印一个。另外,你能有跨越两行的标记吗?

【讨论】:

  • 单行 cmets 以井号字符 # 而不是 // :) 开始
  • 每行只有一个匹配项,但每个文件有多个匹配项。文件示例 - { "Reservations": [ { "OwnerId": "153_Peter", "ReservationId": "r-TempDev", "VolumeId": "i-0vol23_87bcf",
  • Andrea - 你建议的代码就像一个魅力。谢谢。有没有办法说第一个匹配= a,然后第二个匹配= b等等?所以我可以稍后调用这些变量。
猜你喜欢
  • 1970-01-01
  • 2019-04-08
  • 2011-03-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多