小编Håk*_*Lid的帖子

有没有办法关闭 PdfFileReader 打开的文件?

我打开了很多 PDF,我想在解析后删除这些 PDF,但文件在程序运行完成之前保持打开状态。如何关闭使用 PyPDF2 打开的 PDF?

代码:

def getPDFContent(path):
    content = ""
    # Load PDF into pyPDF
    pdf = PyPDF2.PdfFileReader(file(path, "rb"))

    #Check for number of pages, prevents out of bounds errors
    max = 0
    if pdf.numPages > 3:
        max = 3
    else:
        max = (pdf.numPages - 1)

    # Iterate pages
    for i in range(0, max): 
        # Extract text from page and add to content
        content += pdf.getPage(i).extractText() + "\n"
    # Collapse whitespace
    content = " ".join(content.replace(u"\xa0", " ").strip().split())
    #pdf.close()
    return …
Run Code Online (Sandbox Code Playgroud)

python python-2.7 pypdf2

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

为什么这个Ruby方法返回"void value expression"错误?

我有这个简单的方法

def is_palindrome?(sentence)
  raise ArgumentError.new('expected string') unless sentence.is_a?(String)
  safe_sentence = sentence.gsub(/\W+/, '').downcase
  return safe_sentence == safe_sentence.reverse
end

is_palindrome?"rails"
Run Code Online (Sandbox Code Playgroud)

当我运行它时,我void value expression在第4行得到错误,这是return语句

这有什么不对?

ruby

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

Django REST Framework UserSerializer 中的 keyerror

我正在尝试为新用户的创建 API 处理程序添加一些功能。我有一个关联的 UserProfile 表,我想将新创建的用户添加到其中,并添加 URL 参数的值。

POST api 调用如下所示:

.../api/users/?username=fred&email=me@me.com&password=1234&data=whatever
Run Code Online (Sandbox Code Playgroud)

标准 Django 用户表的序列化程序是:

class UserSerializer(serializers.ModelSerializer):
    class Meta:
        model = User
        fields = ('id', 'username', 'password', 'email')
        write_only_fields = ('password',)
        read_only_fields = ('id',)

    def create(self, validated_data):
        the_user = User.objects.create(
            username=validated_data['username'],
            email=validated_data['email']
        )

        the_user.set_password(validated_data['password'])
        the_user.save()

        # Create associated user profile
        user_profile = UserProfile.objects.create(
            data=validated_data['data'],
            user=the_user.id
        )
        user_profile.save()

        return the_user
Run Code Online (Sandbox Code Playgroud)

用户内容的视图是:

class UserViewSet(viewsets.ModelViewSet):
    """
    API endpoint that allows users to be viewed or edited.
    """
    queryset = User.objects.all().order_by('-date_joined')
    serializer_class = UserSerializer
Run Code Online (Sandbox Code Playgroud)

我的新 …

django django-rest-framework

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

什么是防止memcached CacheKeyWarning的好/结构化方法?

我想知道是否有人知道一种方便的方法或方法来确保你传递的钥匙django.core.cache.set()或者没问题cache.get().

来自https://docs.djangoproject.com/en/1.3/topics/cache/#cache-key-warnings:

Memcached是最常用的生产缓存后端,它不允许超过250个字符的缓存键或包含空格或控制字符,并且使用此类键会导致异常.

我在md5_constructor()这里找到了这个函数:https://github.com/django/django/blob/master/django/utils/hashcompat.py,

也许一种方法是md5-如果你总是使用的钥匙?不确定是否安全.

django memcached caching

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

是否可以将 python 函数转换为类?

我是来自 C++ 背景的 Python 新手,这是我第一次看到一种只包含对象的语言。我刚刚了解到类和函数也只是对象。那么,有没有办法将下面的函数转换为类呢?

In [1]: def somefnc(a, b):
...:     return a+b
...: 
Run Code Online (Sandbox Code Playgroud)

我首先尝试将__call__变量分配给以None消除函数的“可调用性质”。但正如您所看到的,__call__成功替换为None但这并没有导致该函数在调用时停止添加数字,尽管在分配给somefnc.__call__(1,3)之前正在工作somefnc.__call__None

In [2]: somefnc.__dict__ 
Out[2]: {}

In [3]: somefnc.__call__
Out[3]: <method-wrapper '__call__' of function object at 0x7f282e8ff7b8>

In [4]: somefnc.__call__ = None

In [5]: x = somefnc(1, 2)

In [6]: print(x)
3

In [7]: somefnc.__call__

In [8]: print(somefnc.__call__(1, 2))
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
ipython-input-8-407663da97ca     
in <module>()
----> 1 print(somefnc.__call__(1, 2)) …
Run Code Online (Sandbox Code Playgroud)

python dynamic-languages python-3.x

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

numpy - arange:为什么以下示例不会在10结束

我是Python的初学者.努力学习numpy.

import numpy as np
x = np.arange(0.5, 10.4, 0.8, int)
Run Code Online (Sandbox Code Playgroud)

它输出:

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

我期待它返回(最后一项是10.4):

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

除此之外,如果我执行此(理解这个例子):

x = np.arange(0.5, 10.4, 0.8)
print(x)
Run Code Online (Sandbox Code Playgroud)

它打印:

[  0.5  1.3  2.1  2.9  3.7  4.5  5.3  6.1  6.9  7.7  8.5  9.3  10.1 ]
Run Code Online (Sandbox Code Playgroud)

python numpy

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

文本位于下方 div 边框顶部

我想让文本出现在 div 的顶部,该 div 的边框也有白色背景,这样您就不会看到边框线穿过文本。我尝试在文本中添加 z-index 但我相信position: relative这并不重要。我也愿意接受有关如何完成的其他建议,并且不想使用 afieldsetlegend

小提琴

#large-div-text {
  padding: 20px;
  border: 1px solid rgba(64, 189, 233, 0.42);
  position: relative;
  margin-top: -10px;
}

#why {
  background-color: #FFF;
  text-align: center;
  z-index: 1000;
}
Run Code Online (Sandbox Code Playgroud)
<div id="why">
  No line behind me, please!
</div>
<div id="large-div-text">
  Large div text
</div>
Run Code Online (Sandbox Code Playgroud)

html css

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

Django通用视图中get_context_data和queryset之间的差异?

Django通用视图get_context_data和之间有什么区别queryset?他们似乎做同样的事情?

python django django-views django-generic-views

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

在 django 管理面板中隐藏应用程序

我的 django 应用程序中安装了django-admin-interface。我使用这个插件配置了布局,我想从管理面板中隐藏它。我的目标是将基本设置存储在数据库中。是否可以?

我在我的代码中找不到与该插件的任何关系。我的代码(settings.py)中只有一处出现了短语 admin_interface 。

INSTALLED_APPS = [
    'mainapp.apps.MainappConfig',
    'admin_interface',
    'colorfield',
    'flat_responsive',
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'django_extensions',
    'smart_selects',
    'activatable_model',
    'bootstrap3',
    'mainapp.apps.ConstanceConfig',
    'constance.backends.database',
    'kronos',
    'ckeditor',
    'django_admin_listfilter_dropdown',
]
Run Code Online (Sandbox Code Playgroud)

是否可以在管理面板中隐藏该区域? 在此输入图像描述

django django-admin

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

如何从python中的字符串中删除""?

我正在尝试从Facebook提取数据,但在抓取时,我陷入了unicode类型错误.实际上我试图抓取的文字包含如下信息:

Hi, this is text
Run Code Online (Sandbox Code Playgroud)

抛出unicodeEncodeError异常的代码如下:

driver.find_elements_by_xpath('//p').text
Run Code Online (Sandbox Code Playgroud)

有任何提示要克服这个问题.

python scrapy selenium-webdriver

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