亚洲国产日韩欧美一区二区三区,精品亚洲国产成人av在线,国产99视频精品免视看7,99国产精品久久久久久久成人热,欧美日韩亚洲国产综合乱

Python讀寫Json涉及到中文的處理方法

原創(chuàng) 2017-01-16 13:24:24 347
摘要:今天在幫前端準(zhǔn)備數(shù)據(jù)的時(shí)候,需要把數(shù)據(jù)格式轉(zhuǎn)成json格式,說實(shí)話,涉及到中文有時(shí)候真的是很蛋疼,除非對Python的編碼規(guī)則比較了解,不然處理起來真的很蛋疼。整個(gè)邏輯我們需要處理的是把一些文章處理,生成多個(gè)html文件,然后用json來顯示文章的列表,圖片,摘要和標(biāo)題。思路為了以后的數(shù)據(jù)擴(kuò)展,那必須有一個(gè)數(shù)據(jù)庫,我的想法就是自己寫一個(gè)簡單的網(wǎng)頁做為提交輸入,然后post到后臺(tái)以后錄入到數(shù)據(jù)庫中,

今天在幫前端準(zhǔn)備數(shù)據(jù)的時(shí)候,需要把數(shù)據(jù)格式轉(zhuǎn)成json格式,說實(shí)話,涉及到中文有時(shí)候真的是很蛋疼,除非對Python的編碼規(guī)則比較了解,不然處理起來真的很蛋疼。

整個(gè)邏輯

我們需要處理的是把一些文章處理,生成多個(gè)html文件,然后用json來顯示文章的列表,圖片,摘要和標(biāo)題。

思路

為了以后的數(shù)據(jù)擴(kuò)展,那必須有一個(gè)數(shù)據(jù)庫,我的想法就是自己寫一個(gè)簡單的網(wǎng)頁做為提交輸入,然后post到后臺(tái)以后錄入到數(shù)據(jù)庫中,再寫一個(gè)展示文章的頁面,展示效果正確后,寫一個(gè)requests動(dòng)態(tài)的把所有的數(shù)據(jù)都爬下來生成一個(gè)一個(gè)的html文檔。最后的json數(shù)據(jù)我只要從數(shù)據(jù)庫把數(shù)據(jù)抽出來生成就行了。

前端

其實(shí)前端的東西很簡單,最近一直在寫網(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<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è)簡單的表單

index.html

<!DOCTYPE html>
<html lang="en">
<head>  
<meta charset="UTF-8">  
<title>Title</title>  
<link href="http://libs.baidu.com/bootstrap/3.0.3/css/bootstrap.min.css" rel="stylesheet">  
<script src="http://libs.baidu.com/jquery/2.0.0/jquery.min.js"></script>  
<script src=" 
</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>

展示的頁面

{% 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來處理了一些數(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):
  """
  請求網(wǎng)頁數(shù)據(jù)后把網(wǎng)頁源碼存儲(chǔ)為html格式,啟動(dòng)腳本時(shí)要先啟動(dòng)Django的Server
  :param file_name:生成文件名的前綴,最后一位用傳入的數(shù)字來代替
  :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

說實(shí)話,json的使用方式很簡單,Python對json的支持也很好,不過涉及到中文就有點(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è)空列表,用來裝生成的字典信息,然后從sqlite里面把之前存的數(shù)據(jù)全部抓出來。把數(shù)據(jù)循環(huán)生成自己想要的格式的字典,一個(gè)一個(gè)的插到列表中。再用Python提供的json.dumps方法把數(shù)據(jù)轉(zhuǎn)成json格式,再寫入文件就行了。 
邏輯看上去是沒什么問題,實(shí)現(xiàn)起來也很完美,但是最后我打開json文件檢查的時(shí)候發(fā)現(xiàn)所有的中文都變成Unicode了。這簡直是坑爹啊。 

大致查了一下,好像網(wǎng)絡(luò)上對這塊說的內(nèi)容并不詳細(xì),舉得例子也都是非常非常簡單的那種,直接給中文的,并不是我想要的,最后只能硬著頭皮去看官方的說明,最后找到了這么一個(gè)東西ensure_ascii=False,在Python轉(zhuǎn)Json的時(shí)候帶上這個(gè)方法,也就是

final_json = json.dumps(list_json, sort_keys=True, indent=4, ensure_ascii=False)

這樣處理之后,寫入文件就是正常的中文了。

更多關(guān)于Python讀寫Json涉及到中文的處理方法請關(guān)注PHP中文網(wǎng)(ipnx.cn)其他文章!

發(fā)布手記

熱門詞條