如果没有线路启动给很多单引号和行括号

2024-09-28 01:22:57 发布

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

我尝试用Apache解析器获取以下地址:

for r in log: 
    host_line = "'",r['host'],"'"
    for line in host_line:
        if not line.startswith("178.255.20.20"):
            print line.strip()

此代码的结果是:

^{pr2}$

使用line.replace("'", "")我删除了单引号。在

print line.replace("'", "")

结果是:

p4fdf6780.dip0.t-ipconnect.de


79.223.103.128


p4fdf6780.dip0.t-ipconnect.de

这给我留下了两个断线。在

怎样才能避免这些断线? 有没有一个解决办法,或者更好的解决方案-更像Python的方式来得到我想要的东西?在


Tags: inloghost解析器for地址apacheline
3条回答

只需像下面这样更改代码。您不需要使用replace函数。在

for r in log: 
    host_line = "'",r['host'],"'"
    for line in host_line:
        if not line.startswith("178.255.20.20"):
            if not line == "'":
                print line.strip()

你想让程序做什么?for line in host_line循环的目的是什么?在

如果您只是在寻找178.255.20.20以外的打印主机,下面的操作会不会不起作用?在

for r in log: 
    host = str(r['host']).strip() # not sure if the str() is required, depends on type of r['host']
    if not host.startswith("178.255.20.20"):
        print host

一种方法是使用bash和一个专用的搜索工具,比如Ag,或者仅仅使用一个标准的grep,因为它是C:

grep -v "178.255.20.20" your_log.txt | grep -v -E "^'"

如果您需要坚持使用python,那么最好使用strip,这样它也会删除引号字符,并且只有在不为空时才打印行:

^{pr2}$

相关问题 更多 >

    热门问题