【问题标题】:Can this Python code be further shrunk?这个 Python 代码可以进一步缩小吗?
【发布时间】:2015-06-04 09:26:30
【问题描述】:

以下是获取域中所有子域的 Python 代码。它需要一个包含网站页面源的文件作为输入。第二个参数是域名。例如:"https://www.sometime.com"

import re
def getSubDomains(fil,domain):
   with open(fil) as f:
    subDomainLst = []
    for line in f:
      m = re.findall(r'\bhref="\https://[\w+\.*]+%s/'%domain,line)
      if(m):
         for ele in m: subDomainLst.append(ele.split('/')[2])
      else:
            continue
   subDomainLst = list(set(subDomainLst))
   for ele in subDomainLst: print ele 
def main():
    fil1,domain1 = raw_input("Enter the file name\n"),raw_input("Enter the domain\n")
    getSubDomains(fil1,domain1)
main() if __name__ == '__main__' else Pass

我尝试将内部的“if else 语句”缩小为

for ele in m: subDomainLst.append(ele.split('/')[2]) if(m) else continue

但这给出了一个错误。

上面的代码是否可以进一步缩小(目前为 16 行),使其占用最少的行数并变得更加 Python 化?

【问题讨论】:

  • 您可以完全删除 else: continue 部分,因为它一开始就不需要。
  • 请注意,“这样它会占用最少的行数并变得更加 Python 化?” 可以是互斥的 - Python 优先考虑代码的可读性 ,并且为了压缩而压缩是不好的形式(缺少空格、单字符标识符等)阅读the style guide,并解释为什么你希望它更短。
  • @Frederic 你的建议是血统,但我已经想通了。可以将大写字母用作“继续”而不是“继续”。所以最后一行 as will be for ele in m: subDomainLst.append(ele.split('/')[2]) if(m) else Continue
  • @jonrsharpe 我欢迎您的建议。在这里,我试图将此程序作为对我的同伴的挑战/竞争,以编写最短的代码。所以我的必须是最短的。
  • @Harvey 竞争长度有什么意义?为什么不改变挑战,编写最简洁代码或最高效代码?竞争的一个重点是磨练你的技能,在这种情况下,你似乎磨练了错误的技能。

标签: python coding-style


【解决方案1】:

您不需要添加继续。您可以尝试这样做,尽管我不建议这样做,因为它会使代码不可读。

subDomainLst = [ele.split('/')[2] for line in f for ele in re.findall(r'\bhref="\https://[\w+\.*]+%s/' % domain, line)]

顺便说一句,您应该将代码缩进 4 个空格,并尽量避免单行难以理解的语句:pythonic 意味着也可读

完整代码:

if __name__ == '__main__':
    import re 
    fil, domain = raw_input("Enter the file name\n"), raw_input("Enter the domain\n")
    with open(fil) as f:
        print '\n'.join([ele.split('/')[2] for line in f for ele in re.findall(r'\bhref="\https://[\w+\.*]+%s/' % domain, line)])

【讨论】:

  • 明白你的意思。这将作为最短行代码的挑战。
  • 我把它写在一行上,因为“目标”是让它变短。
  • 干杯。你是一颗宝石。
【解决方案2】:

您可能希望将if 语句更改为try..except

try:
    for ele in m: subDomainLst.append(ele.split('/')[2])
except TypeError:
    print "OMG m is not iterable!"

或者类似的东西

【讨论】:

    【解决方案3】:

    您有两个不同的目标:缩小线条并变得更加 Python。 这是一行,但不是pythonic:

    import re;fil,domain = raw_input("Enter the file name\n"),raw_input("Enter the domain\n");print '\n'.join(set(ele.split('/')[2] for line in open(fil) for ele in (re.findall(r'\bhref="\https://[\w+\.*]+%s/'%domain,line) or ())))
    

    【讨论】:

    • 除 ';' 以外的任何内容将不胜感激。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-03
    相关资源
    最近更新 更多