代码之家  ›  专栏  ›  技术社区  ›  Azamat

如何将表的标签解析为pandas df

  •  0
  • Azamat  · 技术社区  · 3 年前

    这个网站上有一张桌子 https://www.localeplanet.com/icu/iso3166.html

    我想解析这个国家的列ID和ICU区域设置 但对于这个国家的ICU地区,只有第一行“ca-AD”中的语言代码

    到目前为止,我已经编写了以下代码:

    r = requests.get("https://www.localeplanet.com/icu/iso3166.html") 
    soup = bs4.BeautifulSoup(r.text, "html.parser")
    data = []
    rows = soup.find_all('tr')
    for row in rows:
        cols = row.find_all('td')
        cols = [ele.text.strip() for ele in cols]
        data.append([ele for ele in cols if ele])
    

    如何仅从第二列中提取语言代码?

    0 回复  |  直到 3 年前
        1
  •  2
  •   Nicola Fanelli    3 年前

    你可以做的第一件事就是订购你的输出,并为它做好准备 DataFrame 使用字典而不是列表。我稍微修改了你的代码,以使用字典:

    data = {}
    rows = soup.find_all('tr')
    for row in rows:
        cols = row.find_all('td')
        cols = [ele.text.strip() for ele in cols]
        cells = [ele for ele in cols]
        if cells:
            data[cells[0]] = cells[1] # key is country code, value is string to parse
    
    print(data)
    

    其输出:

    {
     'AD': 'Catalan (Andorra)\xa0(ca-AD)',
     'AE': 'Arabic (United Arab Emirates)\xa0(ar-AE)',
     'AF': 'Persian (Afghanistan)\xa0(fa-AF)Pashto (Afghanistan)\xa0(ps-AF)Uzbek (Arabic, Afghanistan)\xa0(uz-Arab-AF)',
     'AG': 'English (Antigua & Barbuda)\xa0(en-AG)',
     'AI': 'English (Anguilla)\xa0(en-AI)',
     ...
    }
    

    现在我们必须应用正则表达式来解析语言代码。每个语言代码都包含在一对括号中,但我们在每个语言代码之前的括号中还有国家的名称。因此,可以获取括号中包含的字符串中的所有元素,并保留在匹配字符串的结果列表中具有奇数索引的元素。
    我们需要记住,我们需要删除每个代码的括号。实现这些操作的代码如下:

    import re
    
    for key, value in data.items():
        print(value)
        strings_matched = re.findall("\([^(]*\)", value)
        codes = strings_matched[1::2] # keep only elements with odd index
        codes = [x[1:-1] for x in codes] # remove opening and closing parenthesis
        data[key] = codes
    
    print(data)
    

    最终的词典如下,可以轻松获取以国家代码开头的语言代码:

    {'AD': ['ca-AD'],
     'AE': ['ar-AE'],
     'AF': ['fa-AF', 'ps-AF', 'uz-Arab-AF'],
     'AG': ['en-AG'],
     'AI': ['en-AI'],
     'AL': ['sq-AL'],
     'AM': ['hy-AM'],
     'AO': ['ln-AO', 'pt-AO'],
     ...
    }