小编mgi*_*son的帖子

re.RegexObject不存在(引发AttributeError)

在我最近的一系列问题中,我问到了与内部人士的混淆argparse.大多数情况下,我想更改定义为的属性:

class FooClass(object):
   def __init__(self):
      self._this_is_a_re=re.compile("foo")
Run Code Online (Sandbox Code Playgroud)

由于它是"受保护的",我想在我用自己的正则表达式替换之前检查这个属性是否存在以及它是否是正则表达式.例如:

import re
myFoo=FooClass()
attr='_this_is_a_re'
if(hasattr(myFoo,attr) and isinstance(getattr(myFoo,attr),re.RegexObject):
   setattr(myFoo,attr,re.compile("bar"))
Run Code Online (Sandbox Code Playgroud)

这会因属性错误而失败,因为RegexObject即使它在文档中,re也没有命名属性.为什么RegexObject已记录但不可用?我应该在那里使用什么?我想我可以说:type(a) is type(b)但是这看起来很难看......

python regex monkeypatching

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

如何在python中"看到"对象的结构

我在python 2.7中工作.我一直在尝试使用tweepy软件包.有一个名为tweepy.models.status对象的对象,其功能在此处定义:https://github.com/tweepy/tweepy/blob/master/tweepy/models.py.

我有一个看起来像这样的函数:

    def on_status(self, status):
        try:
            print status
            return True
        except Exception, e:
            print >> sys.stderr, 'Encountered Exception:', e
            pass
Run Code Online (Sandbox Code Playgroud)

我所指的对象是从on_status函数返回的对象,称为status.当print status行执行时,我将其打印在屏幕上;

tweepy.models.Status对象位于0x85d32ec>

我的问题实际上非常通用.我想知道如何在视觉上打印出这个status对象的内容?我想知道这个对象里面有哪些信息.

我尝试了这种for i, v in status :方法,但它说这些对象不可迭代.并非所有对象属性都在函数定义中描述.

非常感谢!

python introspection object tweepy

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

fortran in fortran

在C代码中看到以下内容是很常见的:

malloc(sizeof(int)*100);
Run Code Online (Sandbox Code Playgroud)

它将返回一个指针,指向一块足以容纳100个整数的内存块.在fortran中有没有相同的东西?


使用案例:

我有一个二进制文件打开为:

open(unit=10,file='foo.dat',access='stream',form='unformatted',status='old')
Run Code Online (Sandbox Code Playgroud)

我知道该文件包含"记录",其中包含一个包含20个整数,20个实数和80个字符的标题,然后是另一个N实数.每个文件可以有数百条记录.基本上,我想读取或写入此文件中的特定记录(N为简单起见假设为固定常量).

如果我知道每个数据类型的大小,我可以轻松计算我想写的文件中的位置:

header_size = SIZEOF_INT*20 + SIZEOF_FLOAT*20 + SIZEOF_CHAR*80
data_size = N*SIZEOF_FLOAT
position = (record_num-1)*(header_size+data_size)+1
Run Code Online (Sandbox Code Playgroud)

目前我有

!Hardcoded :-(
SIZEOF_INT = 4
SIZEOF_FLOAT = 4
SIZEOF_DOUBLE = 8
SIZEOF_CHAR = 1
Run Code Online (Sandbox Code Playgroud)

有什么方法可以做得更好吗?

限制:

  • 该代码旨在通过各种编译器在各种平台上运行.绝对优选符合标准的解决方案.

fortran sizeof

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

有人可以向我解释一些简单的python概念吗?

我一直在努力学习"以艰难的方式学习Python",到目前为止它已经很顺利,但我有几个问题:

the_count = [1, 2, 3, 4, 5]
fruits = ['apples', 'oranges', 'pears', 'apricots']
change = [1, 'pennies', 2, 'dimes', 3, 'quarters']

# this first kind of for-loop goes through a list
for number in the_count:
    print "This is count %d" % number

# same as above
for fruit in fruits:
    print "A fruit of type: %s" % fruit

# also we can go through mixed lists too
# notice we have to use %r since we don't know what's …
Run Code Online (Sandbox Code Playgroud)

python

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

f2py函数发布GIL

当我调用f2py包装函数时,Global Interpretter Lock(GIL)是否会被释放?

(我很高兴尝试自己发现,但我对numpy来源不太熟悉,知道从哪里开始寻找)......

为了澄清,对这个问题的一个好的答案要么帮助我知道在numpy来源中寻找a的位置,Py_BEGIN_ALLOW_THREADS 或者它只是让我知道GIL是否被释放(最好有一些证据).

python fortran numpy gil f2py

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

沿quadmesh的x轴的日期

我想使用matplotlib并Axes.pcolormesh创建一个情节.我的问题是我希望沿x轴有日期:

import matplotlib.pyplot as plt
fig = plt.figure()
ax = fig.add_subplot(111)
qmesh = ax.pcolormesh(times,mlt,data.T)
fig.colorbar(qmesh,ax=ax)
Run Code Online (Sandbox Code Playgroud)

在这段代码中,times是使用创建的(1D)numpy数组matplotlib.dates.date2num.这创建了一个完全合理的绘图,除了x轴标有值的顺序1e5而不是格式中的日期/时间'%H:%M'.任何建议,将不胜感激.谢谢.

python matplotlib

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

Python:AttributeError:'NoneType'对象没有属性'rfind'

我试图使用os.path.splitext确定文件扩展名

这是我的代码:

for emailid in msgs:
    typ, s = mail.fetch(emailid, "(RFC822)")
    m = email.message_from_string(s[0][1])
    result = re.findall(pattern,str)
    if result:     
        for part in m.walk():
            filename = part.get_filename()
            if filename:
                extension = os.path.splitext(fileName)
                if extension[1][1:] == 'csv':      
                    ### Process into a dataframe
                    df = pd.read_csv(StringIO(filename))
Run Code Online (Sandbox Code Playgroud)

这是来自IPython的错误读数:

#### Begin error Message #####

    AttributeError                            Traceback (most recent call last)
<ipython-input-83-71fabd157c43> in <module>()
     40             if filename:
     41                 print type(filename)
---> 42                 extension = os.path.splitext(fileName)
     43                 if extension[1][1:] == 'csv':
     44                     ### Process into a dataframe …
Run Code Online (Sandbox Code Playgroud)

python file-extension

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

函数声明和大括号之间的C语句

可能重复:
这个C语法有用吗?
在定义中的函数标题之后的C变量声明
这是什么奇怪的C语法?

我正在尝试理解一些代码,它具有以下内容:

int getr(fget)
FILE *fget;
{
   /* More declarations and statements here */
   return (1);
}
Run Code Online (Sandbox Code Playgroud)

以上和之间有什么区别:

int getr(fget)
{
   FILE *fget;
   /* More declarations and statements here */
   return (1);
}
Run Code Online (Sandbox Code Playgroud)

如果是这样,他们有什么不同?

c curly-braces

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

Python“可调用”属性(伪属性)

在 python 中,我可以通过直接分配给属性或通过调用改变属性状态的方法来改变实例的状态:

foo.thing = 'baz'
Run Code Online (Sandbox Code Playgroud)

或者:

foo.thing('baz')
Run Code Online (Sandbox Code Playgroud)

有没有一种很好的方法来创建一个接受上述两种形式的类,该类可以扩展到大量具有这种行为的属性?(很快,我将展示一个我不太喜欢的实现示例。)如果您认为这是一个愚蠢的 API,请告诉我,但也许需要一个更具体的示例。说我有Document课。 Document可以有一个属性title。然而,title可能也希望有一些状态(字体,字体大小,对齐方式,...),但普通用户可能会很高兴只需将标题设置为字符串并完成它...

实现这一目标的一种方法是:

class Title(object):
     def __init__(self,text,font='times',size=12):
         self.text = text
         self.font = font
         self.size = size
     def __call__(self,*text,**kwargs):
         if(text):
             self.text = text[0]
         for k,v in kwargs.items():
             setattr(self,k,v)
     def __str__(self):
         return '<title font={font}, size={size}>{text}</title>'.format(text=self.text,size=self.size,font=self.font)

class Document(object):
     _special_attr = set(['title'])
     def __setattr__(self,k,v):
         if k in self._special_attr and hasattr(self,k):
             getattr(self,k)(v)
         else:
             object.__setattr__(self,k,v)

     def __init__(self,text="",title=""):
         self.title = Title(title)
         self.text = text

     def __str__(self):
         return str(self.title)+'<body>'+self.text+'</body>'
Run Code Online (Sandbox Code Playgroud)

现在我可以按如下方式使用它:

doc = …
Run Code Online (Sandbox Code Playgroud)

python properties

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

使用python中的x和y值将直方图绘制为matplot中的线图

我有两个X轴和Y轴输入值.我想将直方图绘制为折线图.附图中提供了一个例子.我无法使用这些值绘制直方图.

ys = [0.21428571428571427, 0.14285714285714285, 0.047619047619047616, 0.11904761904761904, 0.09523809523809523, 0.09523809523809523, 0.023809523809523808, 0.09523809523809523, 0.11904761904761904, 0.047619047619047616]

xs = [0,1,2,3,4,5,6,7,8,9]
Run Code Online (Sandbox Code Playgroud)

我试过了

plt.hist(xs,ys)
plt.show()
Run Code Online (Sandbox Code Playgroud)

但它失败了.

我对如下图形感兴趣,最好在直方图上有和没有直线.

在此输入图像描述.

X轴和Y轴分配有xs和ys的值.

python linegraph matplotlib histogram

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