繁体   English   中英

我想使用 python 在给定的行号中搜索字符串

[英]I want to search string in given line number using python

下面是输入的sample.txt:

- Name: Xyz
  Info:
    Roll_no: 233421233
    section: A
    Subject:
      - "CS"
- Name: Afe
  Info:
    Roll_no: 3424242425
    section: B
    Subject:
      - "Hum"
- Name: Dgg
  Info:
    Roll_no: sdgfeg
    section: A
    Subject:
      - "CS"
- Name: Xyz
  Info:
   Roll_no: 23452
   section: A
   Subject:
      - "CS"

例子:我搜索字符串xyz也得到了Xyz ,那么我想在line_no+3中搜索23452。

我尝试过的代码:

name = "Xyz"

with open("./sample.txt",r) as f1:
    for num, line in enumerate(f1,1):
        if name in line:
            after the i want to search 23452 using num+3
            and do something

这看起来是 yaml 所以我们可以使用 PyYAML 将其解析为列表/字典结构

import yaml
with open('sample.txt', 'r') as fh:
  data = yaml.load(fh.read())
next(item for item in data if item['Info']['Roll_no'] == '23452')

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM