Python讀寫Json涉及到中文的處理方法
今天在幫前端準(zhǔn)備數(shù)據(jù)的時(shí)候,需要把數(shù)據(jù)格式轉(zhuǎn)成json格式,說(shuō)實(shí)話,涉及到中文有時(shí)候真的是很蛋疼,除非對(duì)Python的編碼規(guī)則比較了解,不然處理起來(lái)真的很蛋疼。
整個(gè)邏輯
我們需要處理的是把一些文章處理,生成多個(gè)html文件,然后用json來(lái)顯示文章的列表,圖片,摘要和標(biāo)題。
思路
為了以后的數(shù)據(jù)擴(kuò)展,那必須有一個(gè)數(shù)據(jù)庫(kù),我的想法就是自己寫一個(gè)簡(jiǎn)單的網(wǎng)頁(yè)做為提交輸入,然后post到后臺(tái)以后錄入到數(shù)據(jù)庫(kù)中,再寫一個(gè)展示文章的頁(yè)面,展示效果正確后,寫一個(gè)requests動(dòng)態(tài)的把所有的數(shù)據(jù)都爬下來(lái)生成一個(gè)一個(gè)的html文檔。最后的json數(shù)據(jù)我只要從數(shù)據(jù)庫(kù)把數(shù)據(jù)抽出來(lái)生成就行了。
前端
其實(shí)前端的東西很簡(jiǎn)單,最近一直在寫網(wǎng)頁(yè),所以前端的東西分分鐘就搞定了。代碼如下:
urls.py
from django.conf.urls import url, include
from . import views
urlpatterns = {
url(r'^$', views.index, name='index'),
url(r'add_article/', views.add_article, name='add_article'),
url(r'^article/(?P<main_id>\S+)/$', views.article, name='article'),
}
views.py
# coding=utf-8
from django.shortcuts import render
from .models import Tzxy
# Create your views here.
def index(request):
return render(request, 'index.html')
def add_article(request):
error = 'error'
if request.method == 'POST':
# 獲取前段request的內(nèi)容
main_id = request.POST['main_id']
img_url = request.POST['img_url']
title = request.POST['title']
content = request.POST['content']
abstract = content[:50]
print main_id
indb = Tzxy(
main_id=main_id,
img_url=img_url,
title=title,
content=content,
abstract=abstract
)
indb.save()
error = 'success'
return render(request, 'index.html', {'error': error})
return render(request, 'index.html')
def article(request, main_id):
article_detial = Tzxy.objects.get(main_id=main_id)
return render(request, 'views.html', {'content': article_detial})
models.py
from __future__ import unicode_literals
from django.db import models
from django.contrib import admin
class Tzxy(models.Model):
main_id = models.CharField(max_length=10)
img_url = models.CharField(max_length=50, null=True)
title = models.CharField(max_length=50)
content = models.TextField()
abstract = models.CharField(max_length=200)
admin.site.register(Tzxy)
模板我就隨便寫了一個(gè)簡(jiǎn)單的表單
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<link rel="stylesheet">
<script src="http://libs.baidu.com/jquery/2.0.0/jquery.min.js"></script>
<script src="http://libs.baidu.com/bootstrap/3.0.3/js/bootstrap.min.js"></script>
</head>
<body>
<form method="post" action="/tzxy/add_article/">
{% csrf_token %}
main_id: <input type="text" name="main_id"><br>
img_url: <input type="text" name="img_url"><br>
title: <input type="text" name="title"><br>
{% if error == 'success' %}
<div class="alert alert-success">{{ error }}</div>
{% endif %}
<textarea name="content" rows="25" style="width: 600px;"></textarea><br>
<input type="submit" name="Submit">
</form>
</body>
</html>
展示的頁(yè)面
{% load custom_markdown %}
<!DOCTYPE html>
<html lang="zh-cn">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="initial-scale=1.0,maximum-scale=1.0,minimum-scale=1.0,user-scalable=no" />
<meta name="apple-touch-fullscreen" content="yes" />
<meta name="apple-mobile-web-app-capable" content="yes" />
<meta name="format-detection" content="telephone=no">
<meta http-equiv="Cache-Control" content="no-store" />
<meta http-equiv="Pragma" content="no-cache" />
<meta http-equiv="Expires" content="0" />
<title>{{ content.title }}</title>
<link rel="stylesheet" href="../../css/cssreset.min.css">
<link rel="stylesheet" href="../../css/fx_tzxy_content.min.css">
</head>
<body>
<div class="page">
<h1>{{ content.title }}</h1>
<div class="content">
{{ content.content | custom_markdown | linebreaksbr }}
</div>
</div>
</body>
</html>
當(dāng)然,我里面使用了markdown來(lái)處理了一些數(shù)據(jù)。有關(guān)markdown的集成,可以移步《Django開發(fā)博客(六)——添加markdown支持》
爬數(shù)據(jù)的小腳本如下,需要使用到requests模塊
# coding=utf-8
import sys
import requests
reload(sys)
sys.setdefaultencoding('utf8')
def tohtml(file_name, startpos, endpos):
"""
請(qǐng)求網(wǎng)頁(yè)數(shù)據(jù)后把網(wǎng)頁(yè)源碼存儲(chǔ)為html格式,啟動(dòng)腳本時(shí)要先啟動(dòng)Django的Server
:param file_name:生成文件名的前綴,最后一位用傳入的數(shù)字來(lái)代替
:param startpos:開始的數(shù)字
:param endpos:結(jié)束的數(shù)字
:return:None
"""
for x in range(startpos, endpos):
r = requests.get('http://127.0.0.1:8000/tzxy/article/' + file_name + str(x))
with open('/Users/SvenWeng/Desktop/test/' + file_name + str(x) + '.html', 'w') as f:
f.write(r.text)
print 'success'
if __name__ == '__main__':
tzhtl_name = 'tzxy_tzhtl_h_'
djjyy_name = 'tzxy_djjyy_h_'
tohtml(djjyy_name, 1, 39)
里面的一些命名自己可以根據(jù)需要去修改。
生成json
說(shuō)實(shí)話,json的使用方式很簡(jiǎn)單,Python對(duì)json的支持也很好,不過(guò)涉及到中文就有點(diǎn)蛋疼了,我的代碼是這樣的:
# coding=utf-8
import sqlite3
import json
import sys
reload(sys)
sys.setdefaultencoding('utf8')
list_json = []
conn = sqlite3.connect('db.sqlite3')
c = conn.cursor()
sql = 'select * from Tzxy_tzxy'
c.execute(sql)
all_thing = c.fetchall()
for x in all_thing:
dic_member = {'id': x[1].split('_')[3],
'img': x[2],
'title': x[3],
'abstract': ''}
list_json.append(dic_member)
conn.close()
final_json = json.dumps(list_json, sort_keys=True, indent=4)
with open('test.json', 'w') as f:
f.write(final_json)
代碼邏輯是:定義一個(gè)空列表,用來(lái)裝生成的字典信息,然后從sqlite里面把之前存的數(shù)據(jù)全部抓出來(lái)。把數(shù)據(jù)循環(huán)生成自己想要的格式的字典,一個(gè)一個(gè)的插到列表中。再用Python提供的json.dumps方法把數(shù)據(jù)轉(zhuǎn)成json格式,再寫入文件就行了。
邏輯看上去是沒(méi)什么問(wèn)題,實(shí)現(xiàn)起來(lái)也很完美,但是最后我打開json文件檢查的時(shí)候發(fā)現(xiàn)所有的中文都變成Unicode了。這簡(jiǎn)直是坑爹啊。
大致查了一下,好像網(wǎng)絡(luò)上對(duì)這塊說(shuō)的內(nèi)容并不詳細(xì),舉得例子也都是非常非常簡(jiǎn)單的那種,直接給中文的,并不是我想要的,最后只能硬著頭皮去看官方的說(shuō)明,最后找到了這么一個(gè)東西ensure_ascii=False,在Python轉(zhuǎn)Json的時(shí)候帶上這個(gè)方法,也就是
final_json = json.dumps(list_json, sort_keys=True, indent=4, ensure_ascii=False)
這樣處理之后,寫入文件就是正常的中文了。
以上這篇Python讀寫Json涉及到中文的處理方法就是小編分享給大家的全部?jī)?nèi)容了,希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。
相關(guān)文章
Python實(shí)現(xiàn)定時(shí)執(zhí)行任務(wù)的三種方式簡(jiǎn)單示例
這篇文章主要介紹了Python實(shí)現(xiàn)定時(shí)執(zhí)行任務(wù)的三種方式,結(jié)合簡(jiǎn)單實(shí)例形式分析了Python使用time,os,sched等模塊定時(shí)執(zhí)行任務(wù)的相關(guān)操作技巧,需要的朋友可以參考下2019-03-03
Tensorflow 模型轉(zhuǎn)換 .pb convert to .lite實(shí)例
今天小編就為大家分享一篇Tensorflow 模型轉(zhuǎn)換 .pb convert to .lite實(shí)例,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2020-02-02
Python3.4實(shí)現(xiàn)遠(yuǎn)程控制電腦開關(guān)機(jī)
這篇文章主要為大家詳細(xì)介紹了Python3.4實(shí)現(xiàn)遠(yuǎn)程控制電腦開關(guān)機(jī)的方法,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2018-02-02
python應(yīng)用程序在windows下不出現(xiàn)cmd窗口的辦法
這篇文章主要介紹了python應(yīng)用程序在windows下不出現(xiàn)cmd窗口的辦法,適用于python寫的GTK程序并用py2exe編譯的情況下,需要的朋友可以參考下2014-05-05
對(duì)pandas將dataframe中某列按照條件賦值的實(shí)例講解
今天小編就為大家分享一篇對(duì)pandas將dataframe中某列按照條件賦值的實(shí)例講解,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2018-11-11
Python使用pyaudio實(shí)現(xiàn)錄音功能
pyaudio是一個(gè)跨平臺(tái)的音頻I/O庫(kù),使用PyAudio可以在Python程序中播放和錄制音頻,本文將利用它實(shí)現(xiàn)錄音功能,并做到停止說(shuō)話時(shí)自動(dòng)結(jié)束2023-05-05

