Commit 385cf781 by qinjiaxin

初次提交。。

parents
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.contrib import admin
# Register your models here.
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.apps import AppConfig
class Dangosign3Config(AppConfig):
name = 'dangoSign3'
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models
# Create your models here.
#!/usr/bin/python
# -*- coding: UTF-8 -*-
import os
import codecs
import jieba
import re
from sklearn.feature_extraction.text import CountVectorizer
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.model_selection import train_test_split
from sklearn.metrics.scorer import make_scorer
from sklearn import linear_model
from sklearn import metrics
from time import time
import numpy as np
from scipy import sparse
from sklearn.utils import shuffle
from sys import argv
from sklearn.naive_bayes import MultinomialNB
# a = argv[1]
a = "【 日期 】 19960813 【 版号 】 5 【 标题 】 我国 矿产资源 知多少 已 发现 矿产 一百六十八种 , 矿床 和 矿点 二十多万 处 【 作者 】 蒋建科 【 正文 】 本报 北京 8 月 1 2 日讯 记者 蒋建科 报道 : “ 过去 常说 咱们 国家 地大物博 、 资源 丰富 , 现在 又 听 广播 、 报纸 说 我们 人均 资源 太 少 , 不知 这次 国际 地质 大会 能 有 啥 说道 ? ” 正在 京城 举办 的 第三十届 国际 地质 大会 也 引起 了 广大 市民 的 关注 和 议论 。 为此 , 记者 走访 了 大会 有关 部门 。 据介绍 , 中国 目前 有 9 5 % 以上 的 一次性 能源 、 8 0 % 以上 的 工业原料 和 大部分 农业 生产资料 均 来自 于 矿产资源 。 截至 1 9 9 4 年底 , 中国 已 发现 矿产 1 6 8 种 , 矿床 和 矿点 2 0 多万 处 , 其中 具有 探明储量 的 矿产 达 1 5 1 种 , 矿产地 2 . 3 万多处 , 可以 说 中国 是 世界 上 矿种 比较 齐全 、 矿产 储量 可观 的 少数几个 国家 之一 。 目前 探明 的 矿产资源 基本 保证 了 国家 经济 建设 的 需求 。 专家 们 指出 , 尽管 中国 矿产资源 总量 大 , 但 人均 占有量 仅为 世界 人均 占有量 的 5 8 % 。 按 统一 的 国际 可比价格 , 中国 矿产资源 潜在 总值 居 世界 第三 , 但 人均 潜在 总值 仅居 世界 第五十三 位 , 而且 矿产资源 还 存在 着 分布 不均 、 一些 矿产 质量 不 优等 特点 。 从 已 探明 的 储量 看 , 煤炭 、 钨 、 锡 、 锑 、 钼 、 汞 等 储量 大 , 开发 条件 好 , 在世界上 占有优势 。 一些 大宗 矿产 , 如铁 、 锰 、 铜 、 钾盐 、 金刚石 等 已 探明储量 不足 , 不能 满足 当前 和 2 0 0 0 年 建设 的 需要 。 中国 幅员辽阔 , 成矿 条件 比较 优越 , 矿产资源 远景 相当可观 , 已 发现 可 作为 进一步 找矿 线索 的 矿点 、 矿化 点有 2 0 多万 处 。 中国 已 探明 的 矿产资源 总量 较大 , 约 占 世界 的 1 2 % , 仅次于 美国 和 俄罗斯 。 以 中国 4 5 种 主要 矿产 保有储量 与 世界 矿产 储量 相 比较 , 有 1 1 种 占 世界 第一位 , 有 1 2 种 占 世界 第二位 。 按 统一 的 国际 市场 可比价格 , 以 1 9 9 4 年 中国 矿产资源 保有量 潜在 价值 计算 , 中国 矿产资源 潜在 总值 为 9 1 . 6 6 万亿元 , 居 世界 第三位 "
test_x = [a]
def split_data_with_label(corpus):
input_x = []
input_y = []
tag = []
if os.path.isfile(corpus):
with codecs.open(corpus, 'r') as f:
for line in f:
tag.append(line)
else:
for docs in corpus:
for doc in docs:
tag.append(doc)
tag = shuffle(tag)
for doc in tag:
index = doc.find(' ')
input_y.append(doc[:index])
input_x.append(doc[index + 1 :])
return [input_x, input_y]
def feature_extractor():
return TfidfVectorizer(token_pattern='\w', ngram_range=(1,2), max_df=0.5, min_df=0.0, stop_words=["是", "的"])
def fit_and_predicted_use_CV(x_path, y_path, test_x, penalty='l2', solver='lbfgs', cv=10):
# clf = linear_model.LogisticRegressionCV(penalty=penalty, solver=solver, n_jobs=-1, cv=cv,multi_class ='auto',max_iter = 500).fit(x_path, y_path)
clf = MultinomialNB().fit(x_path, y_path)
predicted = clf.predict_proba(test_x)
y_path = np.unique(y_path)
i = 0
temp_index_num = 0
final_rank = []
while(i<5):
temp_index_num = np.argmax(predicted)
final_rank.append(y_path[temp_index_num])
predicted[0][temp_index_num] = 0
i = i+1
return final_rank
def main(test_x):
corpus = split_data_with_label('H:\\thu_data_all2')
input_x, y = corpus
count_vec = feature_extractor()
train_x = count_vec.fit_transform(input_x)
test_x1 = count_vec.transform(test_x)
return fit_and_predicted_use_CV(train_x, y, test_x1)
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.test import TestCase
# Create your tests here.
from django.conf.urls import url
from dangoSign3 import views
urlpatterns = [
url(r'^runJob/$', views.run_job),
]
\ No newline at end of file
# -*- coding: utf-8 -*-
from django.http import JsonResponse, HttpResponseNotAllowed, HttpResponse
from django.views.decorators.csrf import csrf_exempt
from rest_framework.parsers import JSONParser
from rest_framework import status
import json
import remark16
def add_args(a, b):
return a+b
# @csrf_exempt
# def run_job(request):
# # 判断请求头是否为json
# if request.content_type != 'application/json':
# # 如果不是的话,返回405
# return HttpResponse('only support json data', status=status.HTTP_415_UNSUPPORTED_MEDIA_TYPE)
# dic = {}
# # 判断是否为post 请求
# if request.method == 'POST':
#
# # 解析请求的json格式入参
# # data = JSONParser().parse(request)
# a = request.POST.get('a', 0)
# b = request.POST.get('b', 0)
# if a and b:
# res = add_args(a, b)
# dic['number'] = res
# dic = json.dumps(dic)
# # return JsonResponse(dic, status=status.HTTP_200_OK)
# return HttpResponse(dic)
# else:
# return HttpResponse("输入错误")
# # except Exception as why:
# # print(why.args)
# else:
# # content = {'msg': 'SUCCESS'}
# # print(data)
# # 返回自定义请求内容content,200状态码
# return HttpResponse("请求方法错误")
# # 如果不是post 请求返回不支持的请求方法
# #return HttpResponseNotAllowed(permitted_methods=['POST'])
@csrf_exempt
def run_job(request):
if request.method == 'POST': # 当提交表单时
s = request.body
s = json.loads(s)
sentence = [s['test_x']]
result = remark16.main(sentence)
data = {'lables':result}
# return HttpResponse(json.dumps(remark16.main(sentence)))
return JsonResponse(data,safe = False)
<?xml version="1.0" encoding="UTF-8"?>
<module type="PYTHON_MODULE" version="4">
<component name="FacetManager">
<facet type="django" name="Django">
<configuration>
<option name="rootFolder" value="$MODULE_DIR$" />
<option name="settingsModule" value="djangoSign3/settings.py" />
<option name="manageScript" value="$MODULE_DIR$/manage.py" />
<option name="environment" value="&lt;map/&gt;" />
<option name="doNotUseTestRunner" value="false" />
<option name="trackFilePattern" value="migrations" />
</configuration>
</facet>
</component>
<component name="NewModuleRootManager" inherit-compiler-output="true">
<exclude-output />
<content url="file://$MODULE_DIR$" />
<orderEntry type="jdk" jdkName="Python 2.7" jdkType="Python SDK" />
<orderEntry type="sourceFolder" forTests="false" />
</component>
<component name="TemplatesService">
<option name="TEMPLATE_CONFIGURATION" value="Django" />
<option name="TEMPLATE_FOLDERS">
<list>
<option value="$MODULE_DIR$/../djangoSign3\templates" />
</list>
</option>
</component>
</module>
\ No newline at end of file
"""
Django settings for djangoSign3 project.
Generated by 'django-admin startproject' using Django 1.11.23.
For more information on this file, see
https://docs.djangoproject.com/en/1.11/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.11/ref/settings/
"""
import os
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/1.11/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'kr+wvdy**md-9@y5w-3u&vc670inr7=q6x8qdtizs!o48a%@%n'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = [
'192.168.243.91',
'192.168.2.240'
]
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'dangoSign3.apps.Dangosign3Config',
]
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
ROOT_URLCONF = 'djangoSign3.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(BASE_DIR, 'templates')]
,
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
WSGI_APPLICATION = 'djangoSign3.wsgi.application'
# Database
# https://docs.djangoproject.com/en/1.11/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
# Password validation
# https://docs.djangoproject.com/en/1.11/ref/settings/#auth-password-validators
AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]
# Internationalization
# https://docs.djangoproject.com/en/1.11/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.11/howto/static-files/
STATIC_URL = '/static/'
# -*- coding: utf-8 -*-
"""djangoSign3 URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.11/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home')
Including another URLconf
1. Import the include() function: from django.conf.urls import url, include
2. Add a URL to urlpatterns: url(r'^blog/', include('blog.urls'))
"""
from django.conf.urls import url, include
from django.contrib import admin
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^', include('dangoSign3.urls')), # 新增
]
"""
WSGI config for djangoSign3 project.
It exposes the WSGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/1.11/howto/deployment/wsgi/
"""
import os
from django.core.wsgi import get_wsgi_application
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "djangoSign3.settings")
application = get_wsgi_application()
#!/usr/bin/env python
import os
import sys
if __name__ == "__main__":
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "djangoSign3.settings")
try:
from django.core.management import execute_from_command_line
except ImportError:
# The above import may fail for some other reason. Ensure that the
# issue is really that Django is missing to avoid masking other
# exceptions on Python 2.
try:
import django
except ImportError:
raise ImportError(
"Couldn't import Django. Are you sure it's installed and "
"available on your PYTHONPATH environment variable? Did you "
"forget to activate a virtual environment?"
)
raise
execute_from_command_line(sys.argv)
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment