【问题标题】:Turning text into a dictionary将文本变成字典
【发布时间】:2020-01-14 09:09:19
【问题描述】:

我已成功提取我的站点地图,我想将网址转换为列表。我不太清楚如何做到这一点,将 https 与修改的日期分开。理想情况下,我还想把它变成一本带有相关日期戳的字典。最后,我打算遍历列表并创建网页的文本文件,并将日期时间戳保存在文本文件的顶部。

我将满足于将其变成列表的下一步。这是我的代码:

import urllib.request
import inscriptis
from inscriptis import get_text
sitemap = "https://grapaes.com/sitemap.xml"
i=0
url = sitemap
html=urllib.request.urlopen(url).read().decode('utf-8')
text=get_text(html)
dicto = {text}
print(dicto)
for i in dicto:
        if i.startswith ("https"):
            print (i + '/n')

输出基本上是带有日期戳、空格和 url 的一行。

【问题讨论】:

标签: python list dictionary web-crawler sitemap


【解决方案1】:

您可以先在空格周围分割文本,然后像这样继续:

text = text.split(' ')
dicto = {}
for i in range(0, len(text), 2):
    dicto[text[i+1]] = text[i]

给出一个以时间戳为键、URL为值的字典,如下:

{
 '2020-01-12T09:19+00:00': 'https://grapaes.com/',
 '2020-01-12T12:13+00:00': 'https://grapaes.com/about-us-our-story/', 
  ...,
 '2019-12-05T12:59+00:00': 'https://grapaes.com/211-retilplast/',
 '2019-12-01T08:29+00:00': 'https://grapaes.com/fruit-logistica-berlin/'
}

我相信你可以从这里开始做进一步的处理。

【讨论】:

    【解决方案2】:

    除了上面的答案:您还可以使用 XML Parser(标准模块)来实现您想要做的事情:

    # Save your xml on disk
    with open('sitemap.xml', 'w') as f:
        f.write(text)
        f.close()
    
    # Import XML-Parser
    import xml.etree.ElementTree as ET
    
    # Load xml and obtain the root node
    tree = ET.parse('sitemap.xml')
    root_node = tree.getroot()
    

    从这里您可以像访问其他所有类似列表的对象一样访问您的 xml 节点:

    print(root_node[1][0].text) # output: 'https://grapaes.com/about-us-our-story/'
    print(root_node[1][1].text) # output: '2020-01-12T12:13+00:00'
    

    从这里创建一个字典就这么简单:

    dicto = dict()
    for child in root_node:
        dicto.setdefault(child[0], child[1])
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-01-02
      • 2021-12-30
      • 2016-06-03
      • 1970-01-01
      • 2022-06-10
      • 2011-01-13
      相关资源
      最近更新 更多