gpt4 book ai didi

python - Unicode错误 python

转载 作者:太空宇宙 更新时间:2023-11-03 12:06:01 24 4
gpt4 key购买 nike

这是问题的要点。我正在尝试从 REST API 调用中获取数据并将它们存储在数据库中。然后我运行几个查询来找出 TOP 3 用户。我无法将从 MySQL 获取的所有列表值打包到 JSON 文件中。

我无法解决以下问题。

File "/Users/id1/Downloads/user1.py", line 58, in get_last_three_installed_user results.append(dict(zip(columns, row)))

TypeError: 'unicode' object is not callable

这是SQL查询的输出

+----------------+--------+-------------+------------+-----------------+
| name | gender | nationality | registered | registered_date |
+----------------+--------+-------------+------------+-----------------+
| mélissa robin | female | FR | 1437761753 | 2015-07-24 |
| agathe fabre | female | FR | 1437002837 | 2015-07-15 |
| soline morin | female | FR | 1436138376 | 2015-07-05 |
+----------------+--------+-------------+------------+-----------------+

如果我尝试 str(name) 我会收到以下错误:

name = str(json_dict["results"][result]["user"]["name"]["first"]) +" "+ str(json_dict["results"][result]["user"]["name"]["last"])

UnicodeEncodeError: 'ascii' codec can't encode character u'\xe4' in position 1: ordinal not in range(128)

这是我的代码:

def get_last_three_installed_user(file_type):
count_sql = "select name,gender,nationality,registered,DATE_FORMAT(from_unixtime(registered), '%Y-%m-%d') registered_date from install_user order by from_unixtime(registered) desc limit 3 "
curs.execute(count_sql)
columns = [column[0] for column in curs.description]
results = []

if file_type == 'csv':
fp = open('user_list.csv', 'w')
csvFile = csv.writer(fp)
rows = curs.fetchall()
csvFile.writerows(rows)
else:
with open('file_count.json', 'w') as outfile:
for row in curs.fetchall():
results.append(dict(zip(columns, row)))
print results
output = {"TableData": results}
json.dump(output, outfile, sort_keys = True, indent = 4, ensure_ascii=False)

最佳答案

这段代码几乎可以解决问题。

def get_last_three_installed_user(file_type):
count_sql = "select name,gender,nationality,registered,DATE_FORMAT(from_unixtime(registered), '%Y-%m-%d') registered_date from install_user order by from_unixtime(registered) desc limit 1,3 "
curs.execute(count_sql)
results = []
dict1 ={}

if file_type == 'csv':
fp = open('user_list.csv', 'w')
csvFile = csv.writer(fp)
rows = curs.fetchall()
csvFile.writerows(rows)
else:
with open('file_count.json', 'w') as outfile:
for row in curs.fetchall():
for idx, col in enumerate(curs.description):
dict1[col[0]] = row[idx]
results.append(dict1)
output = {"TableData": results}
json.dump(output, outfile, sort_keys = True, indent = 4, ensure_ascii=False)

关于python - Unicode错误 python ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32170674/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com