【问题标题】:How to find string with readfile if we know only a part of the string?如果我们只知道字符串的一部分,如何使用 readfile 查找字符串?
【发布时间】:2021-06-21 01:25:36
【问题描述】:

如果我只知道字符串的一部分,如何在文本文件中找到字符串?比如我只知道".someserver.com"

但文件中的整个文本如下所示:

"hostname1.expedite.someserver.com"

所以关键是通过只知道一部分来找到整个名称。

部分文件内容:

{"attributes": {"meta_data": {"created_at":1614882362.179626, "created_by": "admin"}, "site": "AF002"}, hostname:"hostname1.expedite.someserver.com",

【问题讨论】:

  • 能否请您提供文件内容的示例,而不仅仅是需要的部分?
  • 是的,请。我添加了一个示例
  • 您知道您要寻找的房产名称吗?您是否知道在这种情况下您正在寻找hostname:"..." 的属性?
  • 是的,我知道。

标签: python string readfile readline readlines


【解决方案1】:

假设您的数据如下所示:

{"attributes": "xyz", "hostname": ":hostname1.expedite.someserver.com"}
{"attributes": "xyz", "hostname": ":hostname1.expedite.another.com"}
{"attributes": "xyz", "hostname": ":hostname1.expedite.server.com"}
{"attributes": "xyz", "hostname": ":hostname1.expedite.we.com"}
{"attributes": "xyz", "hostname": ":hostname1.expedite.dont.com"}
{"attributes": "xyz", "hostname": ":hostname1.expedite.care.com"}

我们可以:

import ast

check = ".someserver.com"

with open("string.txt", "r") as f:
    line = f.readline()
    while line:
        if check in line:
            print(dict(ast.literal_eval(line))["hostname"])
        line = f.readline()

这会打印我们:

:hostname1.expedite.someserver.com

假设数据如下:

[{"attributes": "xyz", "hostname": ":hostname1.expedite.someserver.com"}, {"attributes": "xyz", "hostname": ":hostname1.expedite.another.com"}, {"attributes": "xyz", "hostname": ":hostname1.expedite.server.com"}, {"attributes": "xyz", "hostname": ":hostname1.expedite.we.com"}, {"attributes": "xyz", "hostname": ":hostname1.expedite.dont.com"}, {"attributes": "xyz", "hostname": ":hostname1.expedite.care.com"}]

然后我们可以:

import json

check = ".someserver.com"

data = json.load(open("string2.txt", "r"))
for d in data:
    if check in d["hostname"]:
        print(d["hostname"])

这给了我们:

:hostname1.expedite.someserver.com

【讨论】:

  • 是的!正是阿尔博!但是文件内容是批量的,不幸的是不是逐行的。 :(
  • 然后可能只是用json.load(f)读入整个blob
【解决方案2】:

假设您的源是包含大量主机名的文件 sample.txt,最简单的方法是使用正则表达式“hostname.someserver.com”,其中通配符 () 是主机名之前的任何内容,并且someserver.com 示例。

import re

f = open("sample.txt", "r")
textfile = f.read()
x = re.findall("hostname.*someserver.com", textfile)
print(x)

【讨论】:

  • 如果数据是在sample.txt中一行一行的,效果很好。但不幸的是,它在我的 sample.txt 中是散装的,所以在这种情况下它会打印出整个文件。
  • 我认为您需要提供有关什么是“批量”的更多信息。你的意思是,你需要消耗多个文本文件?
  • 我的意思是数据不是逐行的,它只是在文本文件中不断地相互跟随。
猜你喜欢
  • 1970-01-01
  • 2023-03-16
  • 1970-01-01
  • 2019-12-02
  • 2018-11-29
  • 1970-01-01
  • 1970-01-01
  • 2020-02-12
  • 2017-12-25
相关资源
最近更新 更多