小编PRM*_*reu的帖子

在python中将文本文件内容转换为字典的最有效方法

以下代码基本上执行以下操作:

  1. 获取文件内容并将其读入两个列表(剥离和拆分)
  2. 将两个列表一起压缩成字典
  3. 使用字典创建"登录"功能.

我的问题是:是否有更简单,更有效(更快)的方法从文件内容创建字典:

文件:

user1,pass1
user2,pass2
Run Code Online (Sandbox Code Playgroud)

def login():
    print("====Login====")

    usernames = []
    passwords = []
    with open("userinfo.txt", "r") as f:
        for line in f:
            fields = line.strip().split(",")
            usernames.append(fields[0])  # read all the usernames into list usernames
            passwords.append(fields[1])  # read all the passwords into passwords list

            # Use a zip command to zip together the usernames and passwords to create a dict
    userinfo = zip(usernames, passwords)  # this is a variable that contains the dictionary in the 2-tuple …
Run Code Online (Sandbox Code Playgroud)

python dictionary file

3
推荐指数
1
解决办法
444
查看次数

werkzeug.routing.BuildError:无法为端点建立网址

我创建了一个Web API来呈现带有导航的网页。下面是我的代码

from flask import Flask, render_template, request

app = Flask(__name__)

@app.route('/testsite/')
def home():
    return render_template('home.html')
if __name__ == '__main__':
    app.run(debug=True)

@app.route('/about/')
def about():

        return render_template('about.html')

if __name__ == '__main__':
    app.run(debug=True)
Run Code Online (Sandbox Code Playgroud)

以下是两个html模板的HTML代码

home.html

<!DOCTYPE html>
<html>
<body>
{% extends "layout.html" %}
{% block content %}
<div class="home">
<h1>My Personal Website</h1>
<p>Hi, this is my personal website.</p>
</div>
{% endblock %}
</body>
</html>
Run Code Online (Sandbox Code Playgroud)

about.html

<!DOCTYPE html>
<html>
<body>
{% extends "layout.html" %}
{% block content %}
<div class="about">
<h1>About me</h1>
<img …
Run Code Online (Sandbox Code Playgroud)

python flask

3
推荐指数
1
解决办法
5993
查看次数

在 Flask-SQLAlchemy 中添加 __init__() 方法

我在 python 3.6.5 中使用 Flask-SQLAlchemy 并且 - 到目前为止 - 无法通过调用__init__(). 我的代码如下所示:

'''
file: models.py
'''
from flask_sqlalchemy import SQLAlchemy
db = SQLAlchemy()

class Network(db.Model):
    __tablename__ = 'network'

    id = db.Column(db.Integer, primary_key=True)
    baud_rate = db.Column(db.Integer)

    def __init__(**kwargs):
        super(Network, self).__init__(**kwargs)  # see note
Run Code Online (Sandbox Code Playgroud)

尝试实例化 Network 对象会导致错误:

>>> n = Network(baud_rate=300)
Traceback (most recent call last):
  File "<console>", line 1, in <module>
TypeError: __init__() takes 0 positional arguments but 1 was given
Run Code Online (Sandbox Code Playgroud)

这有点令人惊讶,因为我使用的是 Flask-SQLAlchemy 文档中给出的配方

如果您出于任何原因决定覆盖构造函数,请确保继续接受 **kwargs 并使用这些 **kwargs …

python flask python-3.x flask-sqlalchemy

3
推荐指数
1
解决办法
2237
查看次数

ModuleNotFoundError:没有名为“ flask_session”的模块

我有一个简单的python文件,尝试将其设置为使用会话,当我运行该文件时,出现以下错误:

ModuleNotFoundError:没有名为“ flask_session”的模块

我相信我已正确导入了模块,是否还有其他可以检查以正确设置的模块?

from flask import Flask, render_template, request, session
from flask_session import Session

app = Flask(__name__)

app.config["SESSION_PERMANENT"] = False
app.config["SESSION_TYPE"] = "filesystem"

Session(app)

@app.route("/", methods=["GET", "POST"])
def index():
    if session.get("notes") is None:
        session["notes"] = []

    if request.method == "POST":
        note = request.form.get("note")
        session["notes"].append(note)

    return render_template("index.html", notes=notes)
Run Code Online (Sandbox Code Playgroud)

这是回溯(最近一次拨打电话)

File "c:\python37\lib\site-packages\flask\cli.py", line 325, in __call__
Open an interactive python shell in this frameself._flush_bg_loading_exception()

File "c:\python37\lib\site-packages\flask\cli.py", line 313, in _flush_bg_loading_exception
reraise(*exc_info)

File "c:\python37\lib\site-packages\flask\_compat.py", line 35, in reraise
raise value

File "c:\python37\lib\site-packages\flask\cli.py", …
Run Code Online (Sandbox Code Playgroud)

python flask

3
推荐指数
3
解决办法
6653
查看次数

在python中为有限状态机分配函数作为变量

我正在尝试用 python 制作游戏,但遇到了根据游戏中的动作让对象切换状态的问题。

我发现最好的方法是使用某种方法将函数(对象的状态)定义为变量,并根据操作赋予对象一个状态。不幸的是,我不确定这是否可行,或者在谈到这个主题时可能有一个我还没有学习的概念。如果有人可以为我的问题提供解决方案,或者只是指出我学习解决问题的方法的方向。

有没有办法将某些函数/方法与名称相关联并避免多个if语句?

class stateUser:

    def __init__(self,state):
        self.state = state

    def executeState(self):
        if self.state == "Print Something":
            self.printSomething()
        elif self.state == "Not Print Something":
            self.dontPrint()
        else:
            self.notUnderstand()
        '''
            would like this function to simply call
            a function that is defined as the object's state,
            instead of using a bunch of if statements
        '''

    def printSomething(self):
        print("Something")

    def dontPrint(self):
        print("No")

    def notUnderstand(self):
        print("I didn't understand that")

runner = stateUser(None)
a = True
while a:
    runner.state = input("Enter …
Run Code Online (Sandbox Code Playgroud)

python oop python-3.x

3
推荐指数
1
解决办法
207
查看次数

BeautifulSoup和类空间

使用BeautifulSoul和Python,我希望find_all所有tr匹配给定类属性的项目包含多个名称,如下所示:

<tr class="admin-bookings-table-row bookings-history-row  paid   ">
Run Code Online (Sandbox Code Playgroud)

我已经尝试了几种匹配该类的方法.正则表达式,通配符,但我总是得到一个空列表.

有没有办法使用正则表达式,通配符或如何匹配此类?

还有就是贴了同样的问题在这里没有答案.

python beautifulsoup

2
推荐指数
2
解决办法
4907
查看次数

Pulp(Python)值错误:需要多于1个值才能解压缩

我正在尝试使用Python上的PuLP 来解决这个问题http://www.me.utexas.edu/~jensen/ORMM/models/unit/linear/subunits/workforce/.

这是我的代码:

from pulp import *

# Create the 'prob' variable to contain the problem data
prob = LpProblem("The Bus Problem",LpMinimize)

# The variables are created with a lower limit of zero
x0=LpVariable("Number of drivers at time 0",0,None,LpInteger)
x4=LpVariable("Number of drivers at time 4",0)
x8=LpVariable("Number of drivers at time 8",0)
x12=LpVariable("Number of drivers at time 12",0)
x16=LpVariable("Number of drivers at time 16",0)
x20=LpVariable("Number of drivers at time 20",0)

# The objective function is added to 'prob' first …
Run Code Online (Sandbox Code Playgroud)

python python-2.7 pulp

1
推荐指数
1
解决办法
326
查看次数

Python:从 YouTube 下载字幕

您好,我尝试使用 YouTube 数据 API 从 YouTube 视频下载字幕。我自定义YouTube 生成的示例代码

    #!/usr/bin/python
    # Usage example:
    # python captions.py --videoid='<video_id>' --name='<name>' --file='<file>' --language='<language>' --action='action'

    import httplib2
    import os
    import sys

    from apiclient.discovery import build_from_document
    from apiclient.errors import HttpError
    from oauth2client.client import flow_from_clientsecrets
    from oauth2client.file import Storage
    from oauth2client.tools import argparser, run_flow


    # The CLIENT_SECRETS_FILE variable specifies the name of a file that contains

    # the OAuth 2.0 information for this application, including its client_id and
    # client_secret. You can acquire …
Run Code Online (Sandbox Code Playgroud)

python youtube oauth youtube-data-api

0
推荐指数
1
解决办法
4395
查看次数

计算列表中数字和字母的数量?

说 list(x) = ["12/12/12", "Jul-23-2017"]

我想计算字母的数量(在这种情况下是 0)和数字的数量(在这种情况下是 6)。

我尝试调用x[i].isalpha()x[i].isnumeric()在迭代 for 循环时抛出错误说明

“类型错误:列表索引必须是整数或切片,而不是 str”

任何帮助将不胜感激!

python python-3.x

0
推荐指数
1
解决办法
2385
查看次数