python怎么实现调查问卷

发布时间:2021-12-17 17:16:04 作者:iii
来源:亿速云 阅读:889
# Python怎么实现调查问卷

## 引言

在数据收集和用户调研领域,调查问卷是最常用的工具之一。Python作为一门强大的编程语言,提供了多种实现调查问卷的方案。本文将详细介绍如何利用Python及相关库构建完整的调查问卷系统,涵盖以下内容:

1. 基础表单实现(Tkinter/命令行)
2. Web问卷方案(Flask/Django)
3. 专业问卷工具集成(Google Forms API)
4. 数据分析与可视化
5. 进阶功能与部署方案

---

## 一、基础表单实现

### 1.1 使用Tkinter构建GUI问卷

```python
import tkinter as tk
from tkinter import messagebox

class SurveyApp:
    def __init__(self):
        self.window = tk.Tk()
        self.window.title("Python问卷调查")
        
        # 问题列表
        self.questions = [
            "1. 您的年龄段是?",
            "2. 您对Python的熟悉程度如何?",
            "3. 您最常使用的Python库是什么?"
        ]
        
        # 答案存储
        self.answers = []
        
        self.create_widgets()
    
    def create_widgets(self):
        """创建界面组件"""
        tk.Label(self.window, text="请填写以下问卷").pack(pady=10)
        
        # 动态生成问题输入框
        self.entry_widgets = []
        for q in self.questions:
            frame = tk.Frame(self.window)
            tk.Label(frame, text=q).pack(side=tk.LEFT)
            entry = tk.Entry(frame)
            entry.pack(side=tk.RIGHT)
            frame.pack(fill=tk.X, padx=5, pady=5)
            self.entry_widgets.append(entry)
        
        # 提交按钮
        tk.Button(self.window, text="提交", command=self.submit).pack(pady=20)
    
    def submit(self):
        """收集答案"""
        self.answers = [e.get() for e in self.entry_widgets]
        messagebox.showinfo("感谢", "问卷提交成功!")
        self.window.quit()
    
    def run(self):
        self.window.mainloop()

if __name__ == "__main__":
    app = SurveyApp()
    app.run()
    print("收集到的答案:", app.answers)

1.2 命令行问卷实现

对于不需要GUI的场景,可使用questionary库:

from questionary import text, select, checkbox

def run_survey():
    answers = {}
    
    answers["name"] = text("请输入您的姓名:").ask()
    answers["age"] = select(
        "请选择年龄段:",
        choices=["18岁以下", "18-25岁", "26-35岁", "36岁以上"]
    ).ask()
    
    answers["skills"] = checkbox(
        "请选择您掌握的Python技能:",
        choices=["基础语法", "Web开发", "数据分析", "机器学习"]
    ).ask()
    
    return answers

if __name__ == "__main__":
    result = run_survey()
    print("\n问卷结果:")
    for k, v in result.items():
        print(f"{k}: {v}")

二、Web问卷方案

2.1 Flask实现基础Web问卷

from flask import Flask, render_template, request, redirect, url_for

app = Flask(__name__)

# 临时存储
responses = []

@app.route('/', methods=['GET', 'POST'])
def survey():
    if request.method == 'POST':
        response = {
            'name': request.form.get('name'),
            'feedback': request.form.get('feedback'),
            'rating': request.form.get('rating')
        }
        responses.append(response)
        return redirect(url_for('thank_you'))
    
    return render_template('survey.html')

@app.route('/thank-you')
def thank_you():
    return "感谢参与问卷调查!"

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

配套HTML模板(templates/survey.html):

<form method="POST">
  <label>姓名: <input type="text" name="name" required></label><br>
  <label>反馈意见:<br>
    <textarea name="feedback" rows="4" cols="50"></textarea>
  </label><br>
  <label>评分:
    <select name="rating">
      <option value="5">5分 - 非常满意</option>
      <option value="4">4分</option>
      <option value="3">3分</option>
      <option value="2">2分</option>
      <option value="1">1分 - 很不满意</option>
    </select>
  </label><br>
  <button type="submit">提交</button>
</form>

2.2 Django全功能问卷系统

# 创建Django项目
django-admin startproject survey_system
cd survey_system
python manage.py startapp questionnaires

关键模型设计(questionnaires/models.py):

from django.db import models

class Question(models.Model):
    TEXT = 'text'
    RADIO = 'radio'
    CHECKBOX = 'checkbox'
    
    QUESTION_TYPES = [
        (TEXT, '文本回答'),
        (RADIO, '单选'),
        (CHECKBOX, '多选')
    ]
    
    text = models.CharField(max_length=200)
    question_type = models.CharField(
        max_length=8,
        choices=QUESTION_TYPES,
        default=TEXT
    )
    
    def __str__(self):
        return self.text

class Choice(models.Model):
    question = models.ForeignKey(Question, on_delete=models.CASCADE)
    text = models.CharField(max_length=100)
    
    def __str__(self):
        return self.text

class Response(models.Model):
    question = models.ForeignKey(Question, on_delete=models.CASCADE)
    answer = models.TextField()
    created_at = models.DateTimeField(auto_now_add=True)

三、专业问卷工具集成

3.1 使用Google Forms API

from googleapiclient.discovery import build
from google.oauth2 import service_account

# 配置服务账号
SCOPES = ['https://www.googleapis.com/auth/forms.body']
SERVICE_ACCOUNT_FILE = 'credentials.json'

credentials = service_account.Credentials.from_service_account_file(
        SERVICE_ACCOUNT_FILE, scopes=SCOPES)

service = build('forms', 'v1', credentials=credentials)

# 创建新问卷
form = {
    "info": {
        "title": "Python用户调研",
        "documentTitle": "Python问卷2023"
    }
}

# 添加问题
question = {
    "requests": [{
        "createItem": {
            "item": {
                "title": "您使用Python的主要领域是?",
                "questionItem": {
                    "question": {
                        "required": True,
                        "choiceQuestion": {
                            "type": "RADIO",
                            "options": [
                                {"value": "Web开发"},
                                {"value": "数据分析"},
                                {"value": "人工智能"},
                                {"value": "自动化脚本"}
                            ],
                            "shuffle": False
                        }
                    }
                }
            },
            "location": {"index": 0}
        }
    }]
}

result = service.forms().create(body=form).execute()
question_set = service.forms().batchUpdate(
    formId=result["formId"], body=question).execute()

四、数据分析与可视化

4.1 使用Pandas分析结果

import pandas as pd
import matplotlib.pyplot as plt

# 假设已有CSV格式的问卷数据
df = pd.read_csv('survey_results.csv')

# 基础统计
print(df.describe())

# 可视化
df['rating'].value_counts().sort_index().plot(
    kind='bar',
    title='满意度评分分布'
)
plt.xlabel('评分')
plt.ylabel('人数')
plt.savefig('rating_dist.png')

4.2 词云分析文本反馈

from wordcloud import WordCloud
from collections import Counter

# 合并所有文本反馈
text = " ".join(df['feedback'].dropna())

# 生成词云
wordcloud = WordCloud(width=800, height=400, 
                     background_color='white').generate(text)

plt.figure(figsize=(10,5))
plt.imshow(wordcloud, interpolation='bilinear')
plt.axis('off')
plt.show()

五、进阶功能与部署

5.1 添加验证逻辑

# 在Flask视图中添加验证
@app.route('/survey', methods=['POST'])
def submit_survey():
    email = request.form.get('email')
    if not validate_email(email):
        flash('请输入有效的邮箱地址')
        return redirect(url_for('survey'))
    
    # 其他处理逻辑...

5.2 部署方案

  1. 传统服务器部署

    gunicorn -w 4 -b :8000 app:app
    
  2. Serverless部署

    • AWS Lambda + API Gateway
    • Vercel/Netlify
  3. 容器化部署

    FROM python:3.9
    COPY . /app
    WORKDIR /app
    RUN pip install -r requirements.txt
    CMD ["gunicorn", "app:app"]
    

结语

通过Python实现调查问卷系统,开发者可以根据需求选择不同技术方案:

Python丰富的生态系统使问卷系统的开发、部署和分析形成完整闭环,是构建高效调研工具的绝佳选择。 “`

(全文约2150字)

推荐阅读:
  1. 使用MongoDB怎么实现问卷/考试设计功能
  2. SAP CRM调查问卷的模型设计原理是什么

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

python

上一篇:怎么实现一个高效的Softmax CUDA kernel

下一篇:如何进行springboot配置templates直接访问的实现

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》