我想知道最简单的方法是将string如下列表转换为list:
x = u'[ "A","B","C" , " D"]'
Run Code Online (Sandbox Code Playgroud)
即使用户在逗号和引号内的空格之间放置空格也是如此.我需要处理它:
x = ["A", "B", "C", "D"]
Run Code Online (Sandbox Code Playgroud)
在Python中.
我知道我可以剥夺的空间与strip()和split()使用拆分操作和检查非字母.但是代码变得非常糟糕.有一个我不知道的快速功能吗?
我有一个小的DataFrame,我想用熊猫绘图.
2 3
0 1300 1000
1 242751149 199446827
2 237712649 194704827
3 16.2 23.0
Run Code Online (Sandbox Code Playgroud)
我还在尝试从熊猫中学习绘图.我想要一个情节在上面的例子中,当我说.
df.plot()
Run Code Online (Sandbox Code Playgroud)
我得到了最奇怪的错误.
Library/Python/2.7/site-packages/pandas-0.16.2-py2.7-macosx-10.10-intel.egg/pandas/tools/plotting.pyc in _compute_plot_data(self)
1015 if is_empty:
1016 raise TypeError('Empty {0!r}: no numeric data to '
-> 1017 'plot'.format(numeric_data.__class__.__name__))
1018
1019 self.data = numeric_data
TypeError: Empty 'DataFrame': no numeric data to plot
Run Code Online (Sandbox Code Playgroud)
虽然我理解DataFrame具有非常不平衡的值,但却是一个非常有趣的情节.我想知道为什么错误消息抱怨没有数字数据要绘制.
如果我理解正确的文档,在python 2.6.5中,字符串格式"{0:d}"将与"%d"一样使用String.format()格式化字符串的方式
" I have {0:d} dollars on me ".format(100.113)
Run Code Online (Sandbox Code Playgroud)
应该打印"我有100美元对我"
但是我得到错误:
ValueError:类型为'float'的对象的未知格式代码'd'
其他格式操作确实有效.例如.
>>> "{0:e}".format(112121.2111)
'1.121212e+05'
Run Code Online (Sandbox Code Playgroud) 我想了解这篇博客文章中发布的mixins的代码.
这些mixin login_required从mixins中调用装饰器django.contrib.auth.decorators,但是它们是由method_decoratorfrom来装饰的django.utils.decorators.在下面的示例代码中,我不明白为什么我需要装饰login_required装饰器.
from django.utils.decorators import method_decorator
from django.contrib.auth.decorators import login_required
class LoginRequiredMixin(object):
"""
View mixin which verifies that the user has authenticated.
NOTE:
This should be the left-most mixin of a view.
"""
# Why do I need to decorate login_required here
@method_decorator(login_required)
def dispatch(self, *args, **kwargs):
return super(LoginRequiredMixin, self).dispatch(*args, **kwargs)
Run Code Online (Sandbox Code Playgroud)
该method_decorator装饰说它是用来"功能装饰转换为一个方法装饰"但在测试代码,我可以用我的装饰,即使没有method_decorator.
我的装饰师
def run_eight_times(myfunc):
def inner_func(*args, **kwargs):
for i in range(8):
myfunc(*args, **kwargs)
return inner_func …Run Code Online (Sandbox Code Playgroud) 我试图理解在Python中创建子类时的使用*args和**kwds.
我想了解为什么这段代码的行为方式.如果我离开了*args,并**kwds在一个呼叫super().__init__,我得到一些奇怪的说法拆包.
这是我的测试用例:
class Animal(object):
def __init__(self, moves, num_legs):
self.moves = moves
self.num_legs = num_legs
def describe(self):
print "Moves :{} , num_legs : {}".format(self.moves, self.num_legs)
class Snake(Animal):
def __init__(self, poisonous, *args, **kwds):
self.poisonous = poisonous
print "I am poisonous:{}".format(self.poisonous)
# This next line is key. You have to use *args , **kwds.
# But here I have deliberately used the incorrect form,
# `args` and `kwds`, and am suprised at …Run Code Online (Sandbox Code Playgroud) 我正在使用PostgeSQL 9.2.2.我的数据库架构是
pg_rocks_post
title | character varying(1024) | not null
body | text | not null
body_title_tsv | tsvector |
body_title_titleupweight_tsv | tsvector |
Run Code Online (Sandbox Code Playgroud)
我创建了body_title_titleupweight_tsv作为类型tsvector.然后,我使用文档中的示例定义了一个触发器,该文档按如下方式对标题进行加权.
pgdj=# CREATE FUNCTION title_upweight_trigger() RETURNS trigger AS $$
begin
new.body_title_titleupweight_tsv :=
setweight(to_tsvector('pg_catalog.english', coalesce(new.title,'')), 'A') ||
setweight(to_tsvector('pg_catalog.english', coalesce(new.body,'')), 'D');
return new;
end
$$ LANGUAGE plpgsql;
Run Code Online (Sandbox Code Playgroud)
我知道触发器有效,因为当我更新pg_rocks_post中的一个条目然后查询它时:我看到它已正确填充了body_title_titleupweight_tsv ts_vector和更新的行.
我的问题是如何将触发器应用于表中的现有行.我只学习postgres,因此我的测试数据库中有几百个条目,想知道如何填充body_title_titleupweight_tsv列.
我认为这样做的一种方法是运行更新并使用类似的东西来编写函数
pgdj=# UPDATE pg_rocks_post SET body_title_titleupweight_tsv =
setweight(to_tsvector( coalesce(title,'')),'A') ||
setweight(to_tsvector(coalesce(body,'')),'D');
Run Code Online (Sandbox Code Playgroud)
而不是在上面的更新语句中再次为触发器重写逻辑.有没有办法通过执行虚拟更新或"触摸"样式操作来触发上面的触发器,该操作会翻转数据库中所有行的触发器.
我试图寻找这种虚拟或"触摸"类型操作的语法或示例,但找不到任何解释如何执行此操作的操作.
我想使用我的 8 核 16 GB ram 工作站快速 bzip2 压缩数百 GB 的数据。目前我正在使用一个简单的 python 脚本来压缩整个目录树,使用 bzip2 和一个 os.system 调用耦合到一个 os.walk 调用。
我看到 bzip2 只使用一个 cpu 而其他 cpu 保持相对空闲。
我是队列和线程进程的新手。但我想知道如何实现这一点,以便我可以有四个 bzip2 运行线程(实际上我猜 os.system 线程),每个线程可能使用自己的 cpu ,当它们 bzip 时会从队列中耗尽文件。
我的单线程脚本粘贴在这里。
import os
import sys
for roots, dirlist , filelist in os.walk(os.curdir):
for file in [os.path.join(roots,filegot) for filegot in filelist]:
if "bz2" not in file:
print "Compressing %s" % (file)
os.system("bzip2 %s" % file)
print ":DONE"
Run Code Online (Sandbox Code Playgroud) 我试图将find命令的结果放到unix bash shell上的文本文件中
使用:
find ~/* -name "*.txt" -print > list_of_txt_files.list
Run Code Online (Sandbox Code Playgroud)
但是list_of_txt_files.list保持为空,我必须终止查找以使其返回命令提示符.我的主目录中有很多txt文件
或者,如何将命令行的结果保存到命令行的文本文件中.我认为这应该有效
我有一个函数接受大量的x,y对作为输入,使用numpy和scipy做一些精细的曲线拟合,然后返回一个值.为了尝试加快速度,我尝试使用Queue.Queue将数据提供给两个线程.数据完成后.我试图让线程终止,然后结束调用进程并将控制权返回给shell.
我试图理解为什么我必须在threading中使用私有方法.线程停止我的线程并将控制返回到命令行.
self.join()不会结束程序.获得控制权的唯一方法是使用私有停止方法.
def stop(self):
print "STOP CALLED"
self.finished.set()
print "SET DONE"
# self.join(timeout=None) does not work
self._Thread__stop()
Run Code Online (Sandbox Code Playgroud)
这是我的代码的近似值:
class CalcThread(threading.Thread):
def __init__(self,in_queue,out_queue,function):
threading.Thread.__init__(self)
self.in_queue = in_queue
self.out_queue = out_queue
self.function = function
self.finished = threading.Event()
def stop(self):
print "STOP CALLED"
self.finished.set()
print "SET DONE"
self._Thread__stop()
def run(self):
while not self.finished.isSet():
params_for_function = self.in_queue.get()
try:
tm = self.function(paramsforfunction)
self.in_queue.task_done()
self.out_queue.put(tm)
except ValueError as v:
#modify params and reinsert into queue
window = params_for_function["window"]
params_for_function["window"] = window + 1
self.in_queue.put(params_for_function)
def …Run Code Online (Sandbox Code Playgroud) 我有一个django应用程序,我成功地接受了heroku.当我在本地干运行collectstatic命令时一切正常.
python manage.py collectstatic --dry-run --noinput
....
Pretending to copy '/Users/hari/.virtualenvs/bsc2/lib/python2.7/site-packages/django/contrib/admin/static/admin/js/admin/ordering.js'
Pretending to copy '/Users/hari/.virtualenvs/bsc2/lib/python2.7/site-packages/django/contrib/admin/static/admin/js/admin/RelatedObjectLookups.js'
71 static files copied.
Run Code Online (Sandbox Code Playgroud)
尽管如此..我的django管理静态文件不会被使用,我在heroku上得到一个简单的django管理站点,Debug设置为False.
如果我将Debug设置为True,我会在heroku上获得一个"丰富"的管理站点.将Debug设置为True或False"git push heroku master"命令终端输出没有关于收集静态文件的任何内容.
我尝试了一个示例"helloworld"应用程序,该应用程序使用来自Heroku的gunicorn并且确实显示了"收集静态"消息.我也尝试将此代码片段插入到我的urls.py中.但这也无济于事.
来自django.conf导入设置
if not settings.DEBUG:
urlpatterns += patterns('',
(r'^static/(?P<path>.*)$', 'django.views.static.serve', {'document_root': settings.STATIC_ROOT}),
Run Code Online (Sandbox Code Playgroud)
接下来,我尝试将以下内容添加到我的heroku配置中
heroku config:add DISABLE_COLLECTSTATIC=0
Run Code Online (Sandbox Code Playgroud)
但这也没有显示我的django管理网站的所有样式.
最后我尝试使用我的Procfile切换到gunicorn,但也没有显示管理员样式.仅设置Debug = True可以显示我的管理样式.
我在Heroku上尝试使用Django 1.4.2和1.5.1,但两者都没有向我显示"正常"的管理站点.有没有办法在没有S3路线的情况下将我的管理文件放在heroku上.
python ×6
django ×2
bzip2 ×1
decorator ×1
django-admin ×1
find ×1
heroku ×1
matplotlib ×1
os.walk ×1
pandas ×1
pipe ×1
postgresql ×1
queue ×1
sql-update ×1
string ×1
triggers ×1
tsvector ×1
unix ×1