基于Flask狗屁不通文章生成器

年前我就晓得github有这么一个项目,挺有意思的,前两天在github下载了源码看了看,跟我想的不大一样…
我看现在市面上有gui版本的、也有纯js实现的,但是没有pythonweb框架去实现的,所以就简单写了一下

原作者将文章生成的思路为:D(主体)=A(名人名言前的垫话)+B(名人名言)+C(名人名言后的垫话)、E(废话)、F(是否另起一段),通过生成随机数,决定是否是D或者E,又或者是F。我这里不改变其思路
讲一下代码,前端就很简单,因为就是生成一个文章,没有过多的功能

<div id="main">
    <div id="title">文章生成器div>
    <div id="name">
        <span>主题span>
        <input id="info">
        <button onclick="getpaper()">生成button>
    div>
    <div id="paper">div>
div>
// 将问题发送到后台,并接收相应
function sendtoserver(text)
{
  var xmlhttp;
  if (window.XMLHttpRequest)
  {
    // IE7+, Firefox, Chrome, Opera, Safari 浏览器执行代码
    xmlhttp=new XMLHttpRequest();
  }
  else
  {
    // IE6, IE5 浏览器执行代码
    xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
  }
  xmlhttp.onreadystatechange=function()
  {
    if (xmlhttp.readyState==4 && xmlhttp.status==200)
    {
      //  相应完成,则显示出来
      // document.getElementById("myDiv").innerHTML=xmlhttp.responseText;
      var answer=xmlhttp.responseText;
      show($.trim(answer));
    }
  }
  xmlhttp.open("POST","/Auto_add",true);
  xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
  // xmlhttp.send("id=bei&q="+$.trim(text));
    xmlhttp.send("id=bei&q="+$.trim(text));
}

function getpaper(){
    // var title=document.getElementById('info').value;
    var title=$('#info').val();
    // window.alert(test);
    sendtoserver(title);
}



function show(data) {
    var p = "
" + data + '
'
; $('#paper').append(p); $('#paper').scrollTop($('#paper')[0].scrollHeight); }

其展示结果大概这样,返回的文章也是在paper这个div内,但是有一个缺点就是没有分段,返回的是整个字符串,没有分段
在这里插入图片描述
重点讲一下后端代码

  • 导入包
from flask import Flask, render_template, request
import random
import json
  • 配置页面路由,返回的是整个页面
app = Flask(__name__)
@app.route('/', methods=['GET', 'POST'])
@app.route('/Auto_index', methods=['GET', 'POST'])
def Auto_index():
    return render_template('Auto_index.html')
  • 配置返回数据的路由,注意这里有一个坑。如果把flask部署到服务器上,如果接收数据,最好用request.form[]去接收,如果用其他的方法可能会有各种各样的意外
@app.route('/Auto_add',methods=['GET','POST'])
def Auto_add():
    id = request.form['id']
    print(id)
    if id == 'bei':
        question = request.form['q']
        answer=getanswer(question)
        # print(answer)
        return answer
    else:
        pass
  • 处理的主体代码
#---------------处理自动生成文章代码
#读取json数据
def getjson(fileName=""):
    with open(fileName,mode='r',encoding="utf-8") as file:
        return json.loads(file.read())
#打乱排序
def ShuffleTraversal(mylist):
    Repeatability=2
    Pond = list(mylist) * Repeatability
    while True:
        random.shuffle(Pond)#打乱
        for element in Pond:
            yield element
#生成D(主体)
def getCelebrityQuotes(CelebrityQuotes,FrontWords,BackWords):
    nextCelebrityQuotes = ShuffleTraversal(CelebrityQuotes)#yield生成了一个生成器,next()可一直调用这个生成器
    xx = next(nextCelebrityQuotes)
    xx = xx.replace(  "a",random.choice(FrontWords) )
    xx = xx.replace(  "b",random.choice(BackWords) )
    return xx

#另起一段
def nextparagraph():
    xx = ". "
    xx += "\r\n"
    xx += "    "
    return xx
  • 处理返回的题目并返回文章数据
def getanswer(question):
    data = getjson("data.json")
    CelebrityQuotes = data["famous"]  # a 代表前面垫话,b代表后面垫话
    FrontWords = data["before"]  # 在名人名言前面弄点废话
    BackWords = data['after']  # 在名人名言后面弄点废话
    nonsense = data['bosh']  # 代表文章主要废话来源
    nextnonsense = ShuffleTraversal(nonsense)
    # nextCelebrityQuotes = ShuffleTraversal(CelebrityQuotes)
    answer=str()
    for x in question:
        tmp = str()
        while ( len(tmp) < 6000 ) :
            Branch = random.randint(0,100)
            if Branch < 5:
                tmp += nextparagraph()
            elif Branch < 20 :
                tmp += getCelebrityQuotes(CelebrityQuotes,FrontWords,BackWords)
            else:
                tmp += next(nextnonsense)
        tmp = tmp.replace("x",question)#json数据中x代表题目事件
        answer += tmp
    return answer
  • flask固定结尾代码

if __name__ == '__main__':
    app.debug=True
    app.run()

我这里上线了,测试了一下,主要就是两个问题

  1. 段落格式没处理好
  2. 重复度较高,因为是以本地json里的数据,也能理解

测试传送门
源码地址
基于Flask狗屁不通文章生成器_第1张图片

你可能感兴趣的:(那些奇淫技巧)