【问题标题】:how to save file list inside list as a json file in python?如何将列表中的文件列表保存为python中的json文件?
【发布时间】:2022-11-10 22:08:52
【问题描述】:

我正在尝试使用python中的beautifulsoap解析来自网站的数据,最后我从网站中提取数据,所以我想将数据保存在json文件中,但它根据我编写的代码将数据保存如下

json文件

[
    {
        "collocation": "\nabove average",
        "meaning": "more than average, esp. in amount, age, height, weight etc. "
    },
    {
        "collocation": "\nabsolutely necessary",
        "meaning": "totally or completely necessary"
    },
    {
        "collocation": "\nabuse drugs",
        "meaning": "to use drugs in a way that's harmful to yourself or others"
    },
    {
        "collocation": "\nabuse of power",
        "meaning": "the harmful or unethical use of power"
    },
    {
        "collocation": "\naccept (a) defeat",
        "meaning": "to accept the fact that you didn't win a game, match, contest, election, etc."
    },

我的代码:

import requests
from bs4 import BeautifulSoup
from selenium import webdriver
import pandas as pd
import json


url = "https://www.englishclub.com/ref/Collocations/"

mylist = [
        "A",
        "B",
        "C",
        "D",
        "E",
        "F",
        "G",
        "H",
        "I",
        "J",
        "K",
        "L",
        "M",
        "N",
        "O",
        "P",
        "Q",
        "R",
        "S",
        "T",
        "U",
        "V",
        "W"
]


list = []


for i in range(23):
    result = requests.get(url+mylist[i]+"/", headers=headers)
    doc = BeautifulSoup(result.text, "html.parser")
    collocations = doc.find_all(class_="linklisting")

    for tag in collocations:
            case = {
                    "collocation": tag.a.string,
                    "meaning": tag.div.string
            }
            list.append(case)


with open('data.json', 'w', encoding='utf-8') as f:

    json.dump(list, f, ensure_ascii=False, indent=4)

但是例如,我想为每个字母创建一个列表,例如,一个列表用于 A,另一个列表用于 B,以便我可以轻松找到哪个字母以哪个字母开头并使用它。我怎样才能做到这一点。正如您在 json 文件中看到的那样,在搭配的开头总是有 \ 我该如何删除它?

【问题讨论】:

  • 对于mylist - 我推荐:list(string.ascii_uppercase)[0:23] 在导入string 之后
  • 搭配总是以换行符 \n 开头 - 如果需要,可以很容易地替换或替换为 ''
  • 你能通过编码来展示我将如何做到这一点@ScottC

标签: python json beautifulsoup


【解决方案1】:
import requests
from bs4 import BeautifulSoup
import pandas as pd
import json


url = "https://www.englishclub.com/ref/Collocations/"

mylist = [
        "A",
        "B",
        "C",
        "D",
        "E",
        "F",
        "G",
        "H",
        "I",
        "J",
        "K",
        "L",
        "M",
        "N",
        "O",
        "P",
        "Q",
        "R",
        "S",
        "T",
        "U",
        "V",
        "W"
]

#you can use dictionary instead list. suits your needs better
list = {}

#just for quick testing, i set range to 4
for i in range(4):
    list[mylist[i]] = [] #make an empty list for your collocations

    result = requests.get(url+mylist[i]+"/")
    doc = BeautifulSoup(result.text, "html.parser")
    collocations = doc.find_all(class_="linklisting")

    for tag in collocations:
            
            case = {
                    "collocation": tag.a.string.replace("
",""),#replace 
 indentations
                    "meaning": tag.div.string
            }
            list[mylist[i]].append(case)#add collocation to related list


with open('data.json', 'w', encoding='utf-8') as f:

    json.dump(list, f, ensure_ascii=False, indent=4)

我已经为更改的部分写了评论。我们为字典中的每个字母创建了一个数组。所以在未来的使用中,你可以只用键来获取它们,而不用担心索引

然而,这是输出

{
    "A": [
        {
            "collocation": "above average",
            "meaning": "more than average, esp. in amount, age, height, weight etc. "
        },
        {
            "collocation": "absolutely necessary",
            "meaning": "totally or completely necessary"
        }
    ],
    "B": [
        {
            "collocation": "back pay",
            "meaning": "money a worker earned in the past but hasn't been paid yet  "
        },
        {
            "collocation": "back road",
            "meaning": "a small country road "
        },
        {
            "collocation": "back street",
            "meaning": "a street in a town or city that's away from major roads or central areas"
        }
    ],
    "C": [
        {
            "collocation": "call a meeting",
            "meaning": "to order or invite people to hold a meeting"
        },
        {
            "collocation": "call a name",
            "meaning": "to say somebody's name loudly"
        },
        {
            "collocation": "call a strike",
            "meaning": "to decide that workers will protest by not going to work "
        }
    ],
    "D": [
        {
            "collocation": "daily life",
            "meaning": "life as experienced from day to day"
        },
        {
            "collocation": "dead ahead",
            "meaning": "straight ahead"
        },
        {
            "collocation": "dead body",
            "meaning": "corpse, or the body of someone who's died"
        }
    ]
}

【讨论】:

    【解决方案2】:

    在您的循环中,定义 doc 后,尝试以下操作:

    for col in doc.select('div.linklisting'):
        print(print(col.select_one('h3 a').text.strip(), "--", col.select_one('div.linkdescription').text))
    

    例如,对于字母 B,它应该输出:

    back pay -- money a worker earned in the past but hasn't been paid yet  
    back road -- a small country road 
    back street -- a street in a town or city that's away from major roads or central areas
    

    等等。您可以将输出元素分配给 CSV、数据框或其他任何内容。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-09-11
      • 2021-03-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-07-11
      相关资源
      最近更新 更多