今天在幫前端準備數(shù)據(jù)的時候,需要把數(shù)據(jù)格式轉成json格式,說實話,涉及到中文有時候真的是很蛋疼,除非對Python的編碼規(guī)則比較了解,不然處理起來真的很蛋疼。
整個邏輯
我們需要處理的是把一些文章處理,生成多個html文件,然后用json來顯示文章的列表,圖片,摘要和標題。
思路
為了以后的數(shù)據(jù)擴展,那必須有一個數(shù)據(jù)庫,我的想法就是自己寫一個簡單的網(wǎng)頁做為提交輸入,然后post到后臺以后錄入到數(shù)據(jù)庫中,再寫一個展示文章的頁面,展示效果正確后,寫一個requests動態(tài)的把所有的數(shù)據(jù)都爬下來生成一個一個的html文檔。最后的json數(shù)據(jù)我只要從數(shù)據(jù)庫把數(shù)據(jù)抽出來生成就行了。
前端
其實前端的東西很簡單,最近一直在寫網(wǎng)頁,所以前端的東西分分鐘就搞定了。代碼如下:
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
\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的內容
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)
模板我就隨便寫了一個簡單的表單
index.html
Title
展示的頁面
{% load custom_markdown %}
{{ content.title }}
{{ content.title }}
{{ content.content | custom_markdown | linebreaksbr }}
當然,我里面使用了markdown來處理了一些數(shù)據(jù)。有關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):
"""
請求網(wǎng)頁數(shù)據(jù)后把網(wǎng)頁源碼存儲為html格式,啟動腳本時要先啟動Django的Server
:param file_name:生成文件名的前綴,最后一位用傳入的數(shù)字來代替
:param startpos:開始的數(shù)字
:param endpos:結束的數(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
說實話,json的使用方式很簡單,Python對json的支持也很好,不過涉及到中文就有點蛋疼了,我的代碼是這樣的:
# 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)
代碼邏輯是:定義一個空列表,用來裝生成的字典信息,然后從sqlite里面把之前存的數(shù)據(jù)全部抓出來。把數(shù)據(jù)循環(huán)生成自己想要的格式的字典,一個一個的插到列表中。再用Python提供的json.dumps方法把數(shù)據(jù)轉成json格式,再寫入文件就行了。
邏輯看上去是沒什么問題,實現(xiàn)起來也很完美,但是最后我打開json文件檢查的時候發(fā)現(xiàn)所有的中文都變成Unicode了。這簡直是坑爹啊。
大致查了一下,好像網(wǎng)絡上對這塊說的內容并不詳細,舉得例子也都是非常非常簡單的那種,直接給中文的,并不是我想要的,最后只能硬著頭皮去看官方的說明,最后找到了這么一個東西 ensure_ascii=False ,在Python轉Json的時候帶上這個方法,也就是
final_json = json.dumps(list_json, sort_keys=True, indent=4, ensure_ascii=False)
這樣處理之后,寫入文件就是正常的中文了。
以上這篇Python讀寫Json涉及到中文的處理方法就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支持腳本之家。
更多文章、技術交流、商務合作、聯(lián)系博主
微信掃碼或搜索:z360901061
微信掃一掃加我為好友
QQ號聯(lián)系: 360901061
您的支持是博主寫作最大的動力,如果您喜歡我的文章,感覺我的文章對您有幫助,請用微信掃描下面二維碼支持博主2元、5元、10元、20元等您想捐的金額吧,狠狠點擊下面給點支持吧,站長非常感激您!手機微信長按不能支付解決辦法:請將微信支付二維碼保存到相冊,切換到微信,然后點擊微信右上角掃一掃功能,選擇支付二維碼完成支付。
【本文對您有幫助就好】元

