小编Rik*_*ggi的帖子

如何检查str(变量)是否为空?

我如何制作:

if str(variable) == [contains text]:
Run Code Online (Sandbox Code Playgroud)

条件?

(或者其他什么东西,因为我很确定我刚写的东西是完全错的)

我有点试图检查random.choice我的列表中是否["",](空白)或包含["text",].

python string conditional-statements

63
推荐指数
6
解决办法
29万
查看次数

TypeError:'int'对象不可调用

给出以下整数和计算

from __future__ import division

a = 23
b = 45
c = 16

round((a/b)*0.9*c)
Run Code Online (Sandbox Code Playgroud)

这导致:

TypeError: 'int' object is not callable.
Run Code Online (Sandbox Code Playgroud)

如何将输出舍入为整数?

python python-2.7

46
推荐指数
3
解决办法
22万
查看次数

使用ElementTree保存XML文件

我正在尝试开发简单的Python(3.2)代码来读取XML文件,进行一些修正并将其存储回来.但是,在存储步骤中,ElementTree会添加此命名空间命名法.例如:

<ns0:trk>
  <ns0:name>ACTIVE LOG</ns0:name>
<ns0:trkseg>
<ns0:trkpt lat="38.5" lon="-120.2">
  <ns0:ele>6.385864</ns0:ele>
  <ns0:time>2011-12-10T17:46:30Z</ns0:time>
</ns0:trkpt>
<ns0:trkpt lat="40.7" lon="-120.95">
  <ns0:ele>5.905273</ns0:ele>
  <ns0:time>2011-12-10T17:46:51Z</ns0:time>
</ns0:trkpt>
<ns0:trkpt lat="43.252" lon="-126.453">
  <ns0:ele>7.347168</ns0:ele>
  <ns0:time>2011-12-10T17:52:28Z</ns0:time>
</ns0:trkpt>
</ns0:trkseg>
</ns0:trk>
Run Code Online (Sandbox Code Playgroud)

代码段如下:

def parse_gpx_data(gpxdata, tzname=None, npoints=None, filter_window=None,
                   output_file_name=None):
        ET = load_xml_library();

    def find_trksegs_or_route(etree, ns):
        trksegs=etree.findall('.//'+ns+'trkseg')
        if trksegs:
            return trksegs, "trkpt"
        else: # try to display route if track is missing
            rte=etree.findall('.//'+ns+'rte')
            return rte, "rtept"

    # try GPX10 namespace first
    try:
        element = ET.XML(gpxdata)
    except ET.ParseError as v:
        row, column = v.position
        print ("error on …
Run Code Online (Sandbox Code Playgroud)

python elementtree

42
推荐指数
2
解决办法
3万
查看次数

在Python上将字符串转换为Date类型

我有这个字符串:

'2012-02-10' # (year-month-day)
Run Code Online (Sandbox Code Playgroud)

我需要它作为日期类型让我使用日期功能isoweekday().

有谁知道如何将此字符串转换为日期?

python string date type-conversion

25
推荐指数
3
解决办法
9万
查看次数

检测字符串中的重复

我有一个简单的问题,但不能带一个简单的解决方案:)

假设我有一个字符串.我想检测一下是否有重复.

我想要:

"blablabla" # => (bla, 3)

"rablabla"  # => (bla, 2)
Run Code Online (Sandbox Code Playgroud)

问题是我不知道我要搜索的模式(我没有"bla"作为输入).

任何的想法?

编辑:
看到评论,我想我应该更多地考虑我的想法:

  • 在字符串中,有一个重复或不重复的模式.
  • 重复的图案可以是任何长度.

如果有一个模式,它将一遍又一遍地重复,直到结束.但是字符串可以在模式的中间结束.

例:

"testblblblblb" # => ("bl",4) 
Run Code Online (Sandbox Code Playgroud)

python regex

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

ElementTree findall()返回空列表

我正在尝试编写一个与last.fm API进行交互的小脚本.

我有一些使用经验ElementTree,但我之前使用它的方式似乎不起作用,它返回一个空列表.
我删除了API密钥,因为我不确切知道它应该是多么私密,并举例说明了我收到的XML.

与API交互的类:

from xml.etree import ElementTree
import urllib
import urllib2

class Last_fmWrapper(object):
    def __init__(self):
        self.last_fm_api_key = '*****************************'
        self.api_url = 'http://ws.audioscrobbler.com/2.0/'
    def get_now_playing(self, last_fm_user, method):
        self.last_fm_user = last_fm_user
        self.method = method
        parameters = {'user':self.last_fm_user, 'api_key':self.last_fm_api_key, 'method':self.method}
        encoded_parameters = urllib.urlencode(parameters)
        request = urllib2.Request(self.api_url, encoded_parameters)
        response = urllib2.urlopen(request)
        api_results = ElementTree.parse(response).findall('track')
        # why does api_results == []?

    def compare_tasteometer(self):
        pass

    def register_user(self):
        pass
Run Code Online (Sandbox Code Playgroud)

调用get_now_playing方法Last_fmWrapper():

from last_fm_wrapper import Last_fmWrapper
last_fm = Last_fmWrapper()
now_playing = last_fm.get_now_playing('BiriBiriRG', 'user.getRecentTracks')
if …
Run Code Online (Sandbox Code Playgroud)

python xml elementtree last.fm

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

如何在线性回归中强制零拦截?

如果这个问题已经得到解答,我有点道歉,我已经看了一眼,找不到我想要的具体内容.

我有一些或多或少的线性数据形式

x = [0.1, 0.2, 0.4, 0.6, 0.8, 1.0, 2.0, 4.0, 6.0, 8.0, 10.0, 20.0, 40.0, 60.0, 80.0]
y = [0.50505332505407008, 1.1207373784533172, 2.1981844719020001, 3.1746209003398689, 4.2905482471260044, 6.2816226678076958, 11.073788414382639, 23.248479770546009, 32.120462301367183, 44.036117671229206, 54.009003143831116, 102.7077685684846, 185.72880217806673, 256.12183145545811, 301.97120103079675]
Run Code Online (Sandbox Code Playgroud)

scipy.optimize.leastsq用来拟合线性回归:

def lin_fit(x, y):
    '''Fits a linear fit of the form mx+b to the data'''
    fitfunc = lambda params, x: params[0] * x + params[1]    #create fitting function of form mx+b
    errfunc = lambda p, x, y: fitfunc(p, x) - y              #create …
Run Code Online (Sandbox Code Playgroud)

python numpy scipy linear-regression

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

Python对象 - 避免创建具有未知名称的属性

希望避免这样的情况:

>>> class Point:
x = 0
y = 0
>>> a = Point()
>>> a.X = 4 #whoops, typo creates new attribute capital x
Run Code Online (Sandbox Code Playgroud)

我创建了以下用作超类的对象:

class StrictObject(object):
    def __setattr__(self, item, value):
        if item in dir(self):
            object.__setattr__(self, item, value)
        else:
            raise AttributeError("Attribute " + item + " does not exist.")
Run Code Online (Sandbox Code Playgroud)

虽然这似乎有效,但python 文档说dir():

注意:因为dir()主要是为了方便在交互式提示中使用而提供,所以它尝试提供一组有趣的名称,而不是尝试提供严格或一致定义的名称集,并且其详细行为可能会在不同版本之间发生变化.例如,当参数是类时,元类属性不在结果列表中.

有没有更好的方法来检查对象是否具有属性?

python attributes object

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

Python领先的下划线_variables

我们知道在类中,使用以下函数时__function__不会导入:

from module import *
Run Code Online (Sandbox Code Playgroud)

有人问什么是_variable?我从来没有一个.
它们存在吗?这是一个变量的概念,无法使用类对象或其他东西访问?

python

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

Python:如何从简单的键和值列表构建一个dict

我有一个值列表,如:

["a", 1, "b", 2, "c", 3]
Run Code Online (Sandbox Code Playgroud)

我想从中建立这样一个词:

{"a": 1, "b": 2, "c": 3}
Run Code Online (Sandbox Code Playgroud)

在Python中使用它的自然方式是什么?

python dictionary list

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