【问题标题】:How to extract domains from the anywhere in the text file?如何从文本文件中的任何地方提取域?
【发布时间】:2017-03-25 14:07:13
【问题描述】:

这是我迄今为止尝试过的:

import re

with open('text.txt', 'r') as fh:
     re.findall(r'^[a-z0-9]([a-z0-9-]+\.){1,}[a-z0-9]+\Z"',fh.readline())
print(p)

我正在尝试从此文件中提取域或 URL:File link
我想知道如何使用正则表达式方法做到这一点。
请建议。

【问题讨论】:

  • 行与行之间是否有换行符?
  • 是的,每个都在一行上。我正在尝试从文件中提取所有域。可能会发生一行有 2 个域,因此需要提取它们。请问你能帮忙吗?

标签: python-3.x


【解决方案1】:

上述文件的每一行看起来都非常像 JSON 编码的字典。
所以这是 json 模块的一个很好的例子:

import json

with open("text.txt", "r") as fh:
    domains = []
    for l in fh.readlines():
        d = json.loads(l)
        domains.append(d["name"])
        # some url domains are located in `value` key for the records which have "type":"cname" 
        if (d["type"] == "cname"): domains.append(d["value"])

print(domains)

输出:

['mail.callfieldcompanion.com', 'reseauocoz.cluster007.ovh.net', 'cluster007.ovh.net', 'ghs.googlehosted.com', 'googlehosted.l.googleusercontent.com', 'isutility.web9.hubspot.com', 'a1049.b.akamai.net', 'plato.mx25.net']

如果输入文件包含单行,请使用以下方法:

import json, re

with open("text.txt", "r") as fh:
    domains = []
    # emulating the list of dictionaries
    line = "[" + re.sub(r'\}\s*\{', '},{',fh.read()) + "]"
    l = json.loads(line)
    for d in l:
        domains.append(d["name"])
        # some url domains are located in `value` key for the records which have "type":"cname"
        if (d["type"] == "cname"): domains.append(d["value"])

print(domains)

【讨论】:

  • 让我试试这个我的朋友。
  • 我收到了这个错误Traceback (most recent call last): File "test.py", line 6, in <module> d = json.loads(l) File "/usr/lib/python3.5/json/__init__.py", line 319, in loads return _default_decoder.decode(s) File "/usr/lib/python3.5/json/decoder.py", line 342, in decode raise JSONDecodeError("Extra data", s, end) json.decoder.JSONDecodeError: Extra data: line 1 column 98 (char 97)
  • @JafferWilson,还记得我的问题行之间是否有换行符??根据您的回答是的,每个都在一行上。我假设每一行都在单独的行上。如果每行都以换行符结尾,它将起作用。 (也许是误会)
  • 糟糕...我检查了我的文件,发现它们没有用换行符分隔...对此我深表歉意。我上次检查过,以为它们是分开的,但似乎没有……有什么我们可以做的吗?
  • 我使用了你的第一种方法,它给了我,现在这个错误:OSError: [Errno 12] Not enough space
猜你喜欢
  • 2017-03-21
  • 1970-01-01
  • 2021-12-13
  • 1970-01-01
  • 2010-09-22
  • 2014-02-05
  • 2016-04-22
  • 1970-01-01
相关资源
最近更新 更多