小编Bio*_*eek的帖子

正则表达式:带可选部分的字符串

我试图解析一些docstrings.

一个示例文档字符串是:

Test if a column field is larger than a given value
    This function can also be called as an operator using the '>' syntax

    Arguments:
        - DbColumn self
        - string or float value: the value to compare to
            in case of string: lexicographic comparison
            in case of float: numeric comparison
    Returns:
        DbWhere object
Run Code Online (Sandbox Code Playgroud)

无论是ArgumentsReturns部分都是可选的.我希望我的正则表达式以组的形式返回描述(第一行),Arguments部分(如果存在)和Returns部分(如果存在).

我现在的正则表达式是:

m = re.search('(.*)(Arguments:.*)(Returns:.*)', s, re.DOTALL)
Run Code Online (Sandbox Code Playgroud)

如果所有三个部件都存在但是一旦失败ArgumentsReturns部件不可用则起作用.我曾尝试使用非贪婪修饰符的几种变体,??但无济于事.

编辑:Arguments …

python regex

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

来自csv.Sniffer的has_header为具有相同布局的文件提供不同的结果

我有以下代码片段:

import csv

def has_header(first_lines):
    sniffer = csv.Sniffer()
    return sniffer.has_header(first_lines) 
Run Code Online (Sandbox Code Playgroud)

first_lines文件的前2048字节在哪里.该函数大部分时间都能正常工作,并返回如下所示True的文件:

SPEC#: 1, SIZE: 18473, TIME: 0.000000
1998.304312 2.15686
1998.773585 3.13725
1999.242914 3.13725
1999.712298 2.7451
2000.181736 2.94118
2000.651230 2.94118
2001.120780 2.15686
2001.590384 2.35294
2002.060043 2.94118
2002.529758 3.13725
2002.999527 2.54902
2003.469352 3.13725
2003.939232 1.96078
2004.409167 1.76471
2004.879158 2.94118
2005.349203 3.72549
2005.819304 3.33333
2006.289459 2.35294
2006.759670 1.76471
2007.229936 3.13725
2007.700258 3.52941
2008.170634 3.92157
2008.641065 3.92157
2009.111552 3.52941
2009.582094 4.70588
2010.052691 3.52941
2010.523343 3.33333
2010.994050 1.37255
2011.464812 2.35294
2011.935630 2.15686 …
Run Code Online (Sandbox Code Playgroud)

python csv

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

如何在Emacs中将当前缓冲区加载到Python解释器中?

我正在尝试使用emacs来编辑和运行python程序(在Ubuntu 10.10上使用emacs23和python 2.6).

  • 我在Emacs(C-x -C-f)中读到了一个文件
  • 我启动了interperter(菜单Python - 启动解释器,我还没有找到键盘快捷键)
  • Emacs将框架分成两个窗口
  • 我把光标放在python文件中(C-x o)

现在我想在下部窗口的Python解释器的上部窗口中运行Python代码.其他地方建议:

  • C-c C-c,但这没有任何作用
  • C-c !,但emacs说该命令未定义

我已经安装了ropemacs(sudo apt-get install python-ropemacs),但没有改变任何东西.

python emacs

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

你可以用给定单词的字母制作4个字母或更多的常用英文单词(每个字母只能使用一次)

在块日历的背面,我发现了以下谜语:

你可以用"教科书"这个词的字母做出多少4个字母或更多的常用英文单词(每个字母只能使用一次).

我想出的第一个解决方案是:

from itertools import permutations

with open('/usr/share/dict/words') as f:
    words = f.readlines()

words = map(lambda x: x.strip(), words)

given_word = 'textbook'

found_words = []

ps = (permutations(given_word, i) for i in range(4, len(given_word)+1))

for p in ps:
    for word in map(''.join, p):
        if word in words and word != given_word:
            found_words.append(word)
print set(found_words)  
Run Code Online (Sandbox Code Playgroud)

这给出了结果,set(['tote', 'oboe', 'text', 'boot', 'took', 'toot', 'book', 'toke', 'betook'])但在我的机器上花费了超过7分钟.

我的下一次迭代是:

with open('/usr/share/dict/words') as f:
    words = f.readlines()

words = map(lambda x: x.strip(), words) …
Run Code Online (Sandbox Code Playgroud)

python puzzle algorithm permutation

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

与cython的numpy数组

我正在尝试将一些python代码移植到cython中,我遇到了一些小问题.

您可以在下面看到代码的代码段(简化示例).

cimport numpy as np
cimport cython
@cython.boundscheck(False) # turn of bounds-checking for entire function
@cython.wraparound(False)
@cython.nonecheck(False)
def Interpolation(cells, int nmbcellsx):
    cdef np.ndarray[float,ndim=1] celle
    cdef int cellnonzero
    cdef int i,l
    for i in range(nmbcellsx):
          celle = cells[i].e
          cellnonzero = cells[i].nonzero
          for l in range(cellnonzero):
               celle[l] = celle[l] * celle[l]
Run Code Online (Sandbox Code Playgroud)

我不明白为什么最内层循环没有完全转换为C代码(即最后一行,celle [l] = ...),请参阅以下输出cython -a feedback:

在此输入图像描述

我在这里错过了什么?

非常感谢.

python numpy cython

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

如何编写在__init __()之后阻止创建新属性的元类?

目前,我__setattr__在类' __init__()方法的末尾覆盖了类' (),以防止创建新属性 -

class Point(object):
    def __init__(self):
        self.x = 0
        self.y = 0
        Point.__setattr__ = self._setattr

    def _setattr(self, name, value):
        if not hasattr(self, name):
            raise AttributeError("'" + name + "' not an attribute of Point object.")
        else:
            super(Point, self).__setattr__(name, value)
Run Code Online (Sandbox Code Playgroud)

有没有办法避免手动覆盖__setattr__()并在元类的帮助下自动执行此操作?

我最近的是 -

class attr_block_meta(type):
    def __new__(meta, cname, bases, dctry):
        def _setattr(self, name, value):
            if not hasattr(self, name):
                raise AttributeError("'" + name + "' not an attribute of " + cname + " object.") …
Run Code Online (Sandbox Code Playgroud)

python metaclass python-2.7

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

运行时错误运行Jest:在React中

我无法运行Jest测试并且有一个非常模糊的错误消息.我在StackOverflow上发现了一个类似的问题,我无法通过在node_module的react文件夹中添加jestSupport的建议来解决它.

引用的问题: 如何使用Jact与React Native

    __tests__/profile-test.js
? Runtime Error
TypeError: Cannot read property 'DEFINE_MANY' of undefined
Run Code Online (Sandbox Code Playgroud)

//来自package.JSON的片段

"scripts": {
    "test": "jest"
  },
  "jest": {
    "scriptPreprocessor": "<rootDir>/node_modules/babel-jest"
  },
Run Code Online (Sandbox Code Playgroud)

//测试文件

import React from 'react';
import ReactDOM from 'react-dom';
import TestUtils from 'react-addons-test-utils';
import Profile from '../components/profile';
jest.setMock('react', {}); // put this in after reading a troubleshooting article

//jest.autoMockOff(Profile);


       describe('Profile'), () => {

        it("renders a form containing user information", function() {
            let Profile = TestUtils.renderIntoDocument(<Profile/>);
            let renderedDOM = () => React.findDOMNode(Profile);

            expect(renderedDOM.tagName).toBe('div');
            expect(renderedDOM.classList).toEqual(['value', 'image', …
Run Code Online (Sandbox Code Playgroud)

unit-testing reactjs jestjs

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

使用TFS 2015运行Jest单元测试

有没有人试图将开玩笑单元测试与TFS 2015集成?我尝试使用Chutzpah测试适配器(https://visualstudiogallery.msdn.microsoft.com/f8741f04-bae4-4900-81c7-7c9bfb9ed1fe?SRC=VSIDE)但是它无法识别开玩笑.我收到以下错误: 无法找到变量Jest

当我通过"npm test"运行单元测试时,我得到了结果.但是为了与TFS 2015集成,我需要一个可以运行Jest单元测试的测试运行器,以便我可以与TFS 2015提供的vstest.console.exe一起运行单元测试,以便它可以管理构建结果​​并在构建中发布结果总结报告.

任何帮助,将不胜感激!!

任何可以使用以下命令运行测试的测试运行器都应该工作(考虑安装在系统上的VS 2015):"C:\ Program Files(x86)\ Microsoft Visual Studio 14.0\Common7\IDE\CommonExtensions\Microsoft\TestWindow\vstest.console .exe""\ test.js"/ UseVsixExtensions:true

unit-testing tfsbuild node.js jestjs visual-studio-2015

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

在Python 2.7中,当我想在其上调用方法时,为什么我必须在括号中包含`int`?

在Python 2.7中,int当我想在其上调用方法时,为什么我必须用括号括起来?

>>> 5.bit_length()
SyntaxError: invalid syntax
>>> (5).bit_length()
3
Run Code Online (Sandbox Code Playgroud)

python

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

无法读取 JEST 中 IF 语句中未定义对象的属性

我有一个简单的 if-else 语句

if(this.props.params.id){
    //do something
}
Run Code Online (Sandbox Code Playgroud)

现在,这在浏览器中运行良好。如果参数中有 id,则进入 if 子句;如果没有 id,则不进入 if 子句。

现在,在用 jest 编写测试时,当未定义 id 时,它会抛出错误:“无法读取未定义的属性'id'”为什么会发生这种情况,不应该将其视为 false 吗?它在浏览器中运行良好,只是在测试时会抛出错误。

javascript reactjs jestjs

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