【问题标题】:Python: Extract matching word starts with number from a line using pythonPython:使用python从一行中提取以数字开头的匹配单词
【发布时间】:2018-08-02 01:41:06
【问题描述】:

我想阅读文本文件并在下面的文本中找到以 5 开头的单词。

“状态”:“OK”}],“PhysicalLocationString”:“rack1/chassis_u1/cpu0/pcie_slot3”,“Physloc”:“0003000101010005”,“PlaceholderNetworkDeviceFunctions”:[{“FC HBA 1”:“51: 40:2E:C0:01:C9:53:E8"}, {"FC HBA 2": "51:40:2E:C0:01:C9:53:EA"}]}}, "零件编号": " P9D94A”、“SerialNumber”:“MY57470DS8”、“状态”:{“Health”:“OK”、“HealthRollup”:“OK”、“State”:“Enabled”}}

我在另一个文件中的输出应该是

51:40:2E:C0:01:C9:53:E8 51:40:2E:C0:01:C9:53:EA

这是我的代码:

    import re
    import sys
    import os

    #get line
    with open('/root/SDFlex/work/cookbooks/ilorest/files/OP.txt', 'r') as file:
    for line in file:
    re.findall(r'\b[s]:\w+', line)
    matchedLine = line
        break


    #and write it to the file
    with open('/root/SDFlex/work/cookbooks/ilorest/files/file.txt', 'w') as 
    file:
         file.write(matchedLine)

请帮忙

【问题讨论】:

  • 这看起来像 JSON 内容,因此您应该在这里使用 JSON 解析器,而不是纯正则表达式解决方案。

标签: python regex shell


【解决方案1】:

使用模式

pattern = '"(5[^"]+)"'
re.findall(pattern, your_string)

它将搜索引用 " 后跟一个 5,然后是除引用之外的任何内容,然后以引用结束。分组将提取您想要的数字。

【讨论】:

  • 给出错误:pattern = "\"(5[^"]+)\"" ^ SyntaxError: invalid syntax
  • 对不起!我用更好的报价修复了它。
【解决方案2】:

感谢 ᴡʜᴀᴄᴋᴀᴍᴀᴅᴏᴏᴅʟᴇ3000 的编辑。

或者:

print(" ".join(filter(lambda x: x.startswith('5'),your_string.split('"'))))

输出:

51:40:2E:C0:01:C9:53:E8 51:40:2E:C0:01:C9:53:EA

在换行符中:

print("\n".join(filter(lambda x: x.startswith('5'),your_string.split('"'))))

【讨论】:

  • 如何放入下一行?比如 51:40:2E:C0:01:C9:53:E8 51:40:2E:C0:01:C9:53:EA
  • 第一行应该是 51:40:2E:C0:01:C9:53:E8 第二行应该是 51:40:2E:C0:01:C9:53:EA
  • @RamKrishna 编辑了我的答案
  • @RamKrishna 很高兴我能帮上忙,?
  • 您不需要list。就做print("\n".join(filter(lambda x: x.startswith('5'),your_string.split('"'))))
【解决方案3】:

你可以试试这个:

" ".join(e for e in your_string.split('"') if e.startswith("5"))

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多