【问题标题】:Python For loop repeats second loop [closed]Python For循环重复第二个循环[关闭]
【发布时间】:2016-05-19 15:12:07
【问题描述】:

我有 2 个文件(a.txt 和 shell.txt)

在 a.txt 中有 59 行,我用正则表达式提取了它们的域

在shell.txt中有5881行。

a.txt 的域存在于 shell.txt 中,如果 a.txt 的域存在于 shell.txt 中,我想提取 shell.txt 的整行

很遗憾,我的循环不能正常工作,所以我想从你们那里得到一些帮助。

谢谢。

import re

s1 = open('a.txt', 'r').read().splitlines()
s2 = open('shell.txt', 'r').read().splitlines()


for x in s1:

    c1 = re.findall("\/\/(.*)\/",x.split("|")[0])[0]

    for x2 in s2:

        c2 = re.findall("\/\/(.*)\/",x2.split("|")[2])

        if c1 == c2:

            print x2

【问题讨论】:

  • 哪里不对?
  • @SirParselot 不起作用,我无法获得 x2 代码 + 如果我在 c2 中打印 c1 for 循环 c1 将重复 300 万次。
  • c2 是列表,但 c1 不是..它应该给出错误
  • 如果我在第二个循环中打印 c2,这些行会打印 346.000+ 次: root@ubuntu:~/links# python a.py > wat root@ubuntu:~/links# wc -l wat 346979 wat root@ubuntu:~/links#
  • 如果你打印 c2,你得到的正是你应该得到的。 59*5881=346979。如果您向我们提供您的文件样本会有所帮助

标签: python regex loops for-loop


【解决方案1】:

首先,尽量不要在内部使用正则表达式进行循环。而是尽可能多地直接从s1s2(没有splitlines())和findall 获取。生成的 c1c2 应该是列表。

要找到两个列表之间的交集,我只需使用集合:

intersects = set(c1).intersection(set(c2))
for intersect in intersects:
    print intersect

如果您在构建所需的正则表达式方面需要帮助,我 将需要了解有关文件以及您要提取的内容的更多信息。

编辑:

对于正则表达式,这可能有效:

regex1 = r"^[^|]*\/\/([^|]*)\/"
c1 = re.findall(regex1, s1, re.M)
regex2 = r"^[^|]*(?:\|[^|]*){2}\/\/([^|]*)\/"
c2 = re.findall(regex2 s2, re.M)

【讨论】:

    猜你喜欢
    • 2013-08-04
    • 2020-10-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-01-11
    • 1970-01-01
    • 2012-04-01
    • 1970-01-01
    相关资源
    最近更新 更多