小编wpe*_*rcy的帖子

使用正则表达式验证用户输入是一个整数

我正在尝试验证用户的输入.我只希望用户能够输入正整数或负整数.所有其他输入(即带字母的任何输入)都应该被拒绝

我现在有下面的代码,但是我收到了错误.我假设它与数据类型有关,但我不确定如何解决这个问题.

import re

number =input("Please enter a number: ")
number=int(number)
while not re.match("^[0-9 \-]+$", number):
    print ("Error! Make sure you only use numbers")
    number = input("Please enter a number: ")
print("You picked number "+ number)
Run Code Online (Sandbox Code Playgroud)

python regex

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

Python3:zip in range

我是Python的新手,我试图将2个列表压缩成1,这是我已经能够做到的.我有2个列表,里面有几个东西,但我要求用户输入一个数字,这应该决定了范围.所以我有List1:A1,A2,A3,A4,A5,A6和List2:B1,B2,B3,B4,B5,B6我知道如何显示2个完整列表,但我正在尝试做什么是,如果用户输入数字"3",则zip应仅显示:(A1,B1),(A2,B2),(A3,B3)而不是整个列表.所以这就是我尝试过的:

a = ["A1", "A2", "A3", "A4", "A5", "A6"]
b = ["B1", "B2", "B3", "B4", "B5", "B6"]
c = zip(a,b)
number = int(input("please enter number"))
for x in c:
    print(x[:number])
Run Code Online (Sandbox Code Playgroud)

但这不起作用.我试着查一查,但找不到任何东西.如果有人可以帮助我,我会很高兴的.

python python-3.x

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

ipython笔记本垂直查看宽熊猫数据框

在 Pandas 0.18.1 中,假设我有一个像这样的数据框:

df = pd.DataFrame(np.random.randn(100,200))
df.head()

    0   1   2   3   4   5   6   7   8   9   10  11  12  13  14  15  16  17  18  19  20  21  22  23  24  25  26  27  28  29  30  31  32  33  
Run Code Online (Sandbox Code Playgroud)

如果我想像这样垂直查看这个怎么办:

0 1 2 3 4 5 
6 7 8 9 10 11
Run Code Online (Sandbox Code Playgroud)

文档指向:

pd.set_option('expand_frame_repr', True)

df

0         1         2         3         4         5         6  \
0 -1.039575  0.271860 -0.424972  0.567020  0.276232 -1.087401 -0.673690   
1  0.404705  0.577046 -1.715002 -1.039268 …
Run Code Online (Sandbox Code Playgroud)

python pandas jupyter-notebook

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

从几个类继承相同的函数名

我正在stackoverflow上阅读这个线程,但根据用户的说法,解决方案似乎是错误的,最重要的是,它无法解决我的问题,我不知道是因为答案是在python 2中还是现在。

但是,可以说我有这个代码

class A:
    def say_hello(self):
        print("Hi")

class B:
    def say_hello(self):
        print("Hello")

class C(A, B):
    def say_hello(self):
        super().say_hello()
        print("Hey")

welcome = C()
welcome.say_hello()
Run Code Online (Sandbox Code Playgroud)

如何在不更改函数名称的情况下从 C 类调用 A 类和 B 类?正如我在另一个线程中读到的那样,您可以执行类似的操作,super(B, self).say_hello()但这似乎不起作用,但我不知道为什么。

python inheritance class python-3.x

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

如何用beautifulsoup4提取HTML?

html看起来像这样:

<td class='Thistd'><a ><img /></a>Here is some text.</td>
Run Code Online (Sandbox Code Playgroud)

我只想得到字符串<td>.我不需要<a>...</a>.我怎样才能做到这一点?

我的代码:

from bs4 import BeautifulSoup
html = """<td class='Thistd'><a><img /></a>Here is some text.</td>"""

soup = BeautifulSoup(html)
tds = soup.findAll('td', {'class': 'Thistd'})
for td in tds:
    print td
    print '============='
Run Code Online (Sandbox Code Playgroud)

我得到的是 <td class='Thistd'><a ><img /></a>Here is some text.</td>

但我只是需要 Here is some text.

python beautifulsoup

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

打印单击按钮的文本tkinter

这是我的代码:

from tkinter import *    

def command(d):
   print(d)

a = Tk()
b = []

for c in range(0, 5):
    b.append(Button(a, text=c, command=lambda: command(c)))
    b[c].pack()

a.mainloop()
Run Code Online (Sandbox Code Playgroud)

运行脚本时,按钮全部打印4,而我希望它们打印显示在它们上面的数字.你怎么能这样做?

我使用的是Python 3.4

python tkinter

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

使用逗号问题将数据从PHP导出到Excel

我的数据库:

我的数据库

由于数据库中"description"字段中的逗号,我将数据导出到excel时遇到问题.

这是我的代码:

<?php 
include 'database.php';
if (isset($_POST['submit'])){
    $filename = 'uploads/'.strtotime("now").'.csv';
    $fp = fopen($filename, "w");
    $sql = "SELECT * FROM data";
    $linkSql = mysqli_query($link,$sql) or die(mysqli_error($link));
    $row = mysqli_fetch_assoc($linkSql);

    $seperator ="";
    $comma = "";
    foreach ($row as $name => $value) {
        $seperator .= $comma . '' .str_replace('','""',$name);
        $comma = ",";
    }
    $seperator .="\n";
    fputs($fp, $seperator);

    mysqli_data_seek($linkSql, 0);

    while($row = mysqli_fetch_assoc($linkSql)){
    $seperator ="";
    $comma = "";
    foreach ($row as $name => $value) {
        $seperator .= $comma . '' .str_replace('','""',$value);
        $comma = …
Run Code Online (Sandbox Code Playgroud)

php excel

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

Postgres:无法选择最佳候选函数

有人可以解释如何解决这个查询吗?

SELECT date_part('month', scheduler_scheduleevents.date), sum(price)
    FROM user_settings_userservices
    JOIN scheduler_scheduleevents
    ON scheduler_scheduleevents.service_type_id = user_settings_userservices.id
    WHERE user_settings_userservices.salonid_id = %s
    AND is_start_time = True and is_active = False
    AND ( date < %s or ( date = %s and time < %s ) )
    AND date_part('year', scheduler_scheduleevents.date) = date_part('year', %s)
    GROUP BY date_part('month', scheduler_scheduleevents.date),
    (request.user.id, now_date, now_date, now_time, now_date, )
    )
Run Code Online (Sandbox Code Playgroud)

当我尝试在 django 应用程序中执行此查询时,我收到此警告:

function date_part(unknown, unknown) is not unique

LINE 9: ...ate_part('year', scheduler_scheduleevents.date) = date_part(...
                                                         ^

HINT:  Could not choose a best …
Run Code Online (Sandbox Code Playgroud)

python sql django postgresql

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

boto3:TypeError:|:'str'和'str'的不支持的操作数类型

我尝试按照http://boto3.readthedocs.io/网页记录测试boto3库.我尝试获取Cloudformation堆栈列表.所以我的代码是:

import boto3
client = boto3.client('cloudformation')
response = client.list_stacks(
    NextToken='string',
    StackStatusFilter=[
          'CREATE_IN_PROGRESS'|'CREATE_FAILED'|'CREATE_COMPLETE'|'ROLLBACK_IN_PROGRESS'|'ROLLBACK_FAILED'|'ROLLBACK_COMPLETE'|'DELETE_IN_PROGRESS'|'DELETE_FAILED'|'DELETE_COMPLETE'|'UPDATE_IN_PROGRESS'|'UPDATE_COMPLETE_CLEANUP_IN_PROGRESS'|'UPDATE_COMPLETE'|'UPDATE_ROLLBACK_IN_PROGRESS'|'UPDATE_ROLLBACK_FAILED'|'UPDATE_ROLLBACK_COMPLETE_CLEANUP_IN_PROGRESS'|'UPDATE_ROLLBACK_COMPLETE'|'REVIEW_IN_PROGRESS',

    ]
)   
print response
Run Code Online (Sandbox Code Playgroud)

当我运行它时,我收到一条错误消息,如:

TypeError: unsupported operand type(s) for |: 'str' and 'str'
Run Code Online (Sandbox Code Playgroud)

那有什么不对吗?我正在使用Python 2.7

python amazon-web-services python-2.7 aws-cloudformation boto3

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

Boto3 列出每个aws安全组中的所有规则

为了获得我使用的所有组:

groups = list(ec2.security_groups.all())
Run Code Online (Sandbox Code Playgroud)

然后:

rules = []
for grp in groups:
   sgid =  grp.group_id
   try:
       response = ec2_client.describe_security_groups(GroupIds=[sgid])
       rules.append(response)
   except ClientError as e:
       print(e)
Run Code Online (Sandbox Code Playgroud)

我留下了一个令人讨厌的 json 来解析:-(。

boto3

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

如果json请求为“ none”,则继续执行“ for”

我正在通过API请求下载json。

问题是这些请求中的一些请求什么都不返回(无),然后显示错误消息,循环停止。

这是错误消息:

raise JSONDecodeError("Expecting value", s, err.value) from None

JSONDecodeError: Expecting value
Run Code Online (Sandbox Code Playgroud)

这是一个小例子:

pessoa_file = open('pessoa_file.txt', 'a', encoding='utf-8')
for x in range(n_pessoas):

    pessoa = jsonresponse['Pessoa'][x]

    response_pessoa = requests.get(pessoa)

    pessoa_data = json.loads(response_pessoa.text)

    pessoa_file.write(pessoa_data)
Run Code Online (Sandbox Code Playgroud)

我想知道如何忽略错误或写点东西。我对python不太熟悉,但是我知道R。我认为它应该类似于try()tryCatch()

python exception

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

从谷歌搜索中提取结果数

我正在编写一个网络抓取工具,以提取出现在搜索结果页面左上角的谷歌搜索中的搜索结果数量。我写了下面的代码,但我不明白为什么phrase_extract 是 None 。我想提取短语“大约 12,010,000,000 个结果”。我在哪一部分犯了错误?可能是 HTML 解析不正确?

import requests
from bs4 import BeautifulSoup

def pyGoogleSearch(word):   
    address='http://www.google.com/#q='
    newword=address+word
    #webbrowser.open(newword)
    page=requests.get(newword)
    soup = BeautifulSoup(page.content, 'html.parser')
    phrase_extract=soup.find(id="resultStats")
    print(phrase_extract)

pyGoogleSearch('world')
Run Code Online (Sandbox Code Playgroud)

例子

python beautifulsoup web-scraping

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

从维基百科表格中抓取数据

我只是想将维基百科表中的数据抓取到熊猫数据框中。

我需要重现三列:“邮政编码、自治市镇、社区”。

import requests
website_url = requests.get('https://en.wikipedia.org/wiki/List_of_postal_codes_of_Canada:_M').text
from bs4 import BeautifulSoup
soup = BeautifulSoup(website_url,'xml')
print(soup.prettify())

My_table = soup.find('table',{'class':'wikitable sortable'})
My_table

links = My_table.findAll('a')
links

Neighbourhood = []
for link in links:
    Neighbourhood.append(link.get('title'))

print (Neighbourhood)

import pandas as pd
df = pd.DataFrame([])
df['PostalCode', 'Borough', 'Neighbourhood'] = pd.Series(Neighbourhood)

df
Run Code Online (Sandbox Code Playgroud)

它只返回自治市镇......

谢谢

python wikipedia beautifulsoup pandas

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