如果我们只知道字符串的一部分,如何使用readfile查找字符串?

2024-09-27 00:21:50 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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

"hostname1.expedite.someserver.com"

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

部分文件内容:

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

Tags: 文件字符串文本com内容data名字meta
2条回答

假设您的源文件是一个包含大量主机名的sample.txt文件,最简单的方法是使用regex“hostname.someserver.com”,其中通配符()在hostname和someserver.com示例之前

import re

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

假设您的数据如下所示:

{"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

相关问题 更多 >

    热门问题