首页 > 解决方案 > UnicodeDecodeError:“charmap”编解码器无法解码位置 191 中的字节 0x81:字符映射到

问题描述

我正在使用 python (flask) 去动态地请求一些国家(151 个国家)的一些数据。对于那个请求,我正在使用urllib图书馆的帮助。当我尝试将字典列表(代表国家/地区的数据)从 app.py 传递到 index.html 时,标题中出现此错误:

UnicodeDecodeError: 'charmap' codec can't decode byte 0x81 in position 191: character maps to <undefined>

我试图在网上寻找一些解决方案,但我找不到该库的任何特定内容。我该如何解码?如果我不知道创建这些文件的编码方法,我应该使用哪种方法?

应用程序.py:

@app.route("/", methods=["GET", "POST"])

def index():
    if request.method=="GET":
        # getting the list of countries in the online database
        url_locations = "https://raw.githubusercontent.com/owid/covid-19-data/master/public/data/vaccinations/locations.csv"

        # storing the list of countries
        locations_page = urllib.request.urlopen(url_locations)
        locations_reader = csv.reader(io.TextIOWrapper(locations_page))
        country_list = []
        for location in locations_reader:
            # avoid the first (header) row where location[0] == "location"
            if location[0] != 'location':
                country_dict = {}
                country_dict['country'] = location[0]
                country_dict['vaccines'] = location[2]
                country_dict['source_name'] = location[4]
                country_dict['source_link'] = location[5]
                # creating a dict with the country info
                url_country_info = "https://raw.githubusercontent.com/owid/covid-19-data/master/public/data/vaccinations/country_data/" + location[0].replace(" ", "%20") + ".csv"
                country_page = urllib.request.urlopen(url_country_info)
                country_reader = csv.reader(io.TextIOWrapper(country_page))

                for data in country_reader:
                    country_dict['total_vaccinations'] = data[4]
                    country_dict['people_vaccinated'] = data[5]
                    country_dict['people_totally_vaccinated'] = data[6]
                country_list.append(country_dict)

        return render_template("index.html", country_list=country_list)

    else:
        # to be completed later
        return render_template("index.html")

索引.html:

<script>
  var country_list = JSON.parse('{{ country_list | tojson }}');
  console.log(country_list);
  var countries = [];
  for (var i = 0; i < country_list.length; i++) {
    countries.push(country_list[i].country);
  }
  console.log(countries);
  autocomplete(document.getElementById('myInput'), countries);
</script>

而且,如果您想看看,这里是我请求的 csv 文件的链接:

https://github.com/owid/covid-19-data/tree/master/public/data

标签: pythoncsvflaskurllib

解决方案


推荐阅读