Questions tagged «python»

Python是一种多范式,动态类型的多用途编程语言。它旨在快速学习,理解和使用并强制使用干净统一的语法。请注意,Python 2自2020年1月1日起已不再受支持。不过,对于特定于版本的Python问题,请添加[python-2.7]或[python-3.x]标签。使用Python变体或库(例如Jython,PyPy,Pandas,Numpy)时,请将其包含在标签中。


6
通过'ElementTree'在Python中使用名称空间解析XML
我有以下要使用Python解析的XML ElementTree: <rdf:RDF xml:base="http://dbpedia.org/ontology/" xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:owl="http://www.w3.org/2002/07/owl#" xmlns:xsd="http://www.w3.org/2001/XMLSchema#" xmlns:rdfs="http://www.w3.org/2000/01/rdf-schema#" xmlns="http://dbpedia.org/ontology/"> <owl:Class rdf:about="http://dbpedia.org/ontology/BasketballLeague"> <rdfs:label xml:lang="en">basketball league</rdfs:label> <rdfs:comment xml:lang="en"> a group of sports teams that compete against each other in Basketball </rdfs:comment> </owl:Class> </rdf:RDF> 我想找到所有owl:Class标签,然后提取其中所有rdfs:label实例的值。我正在使用以下代码: tree = ET.parse("filename") root = tree.getroot() root.findall('owl:Class') 由于命名空间的原因,出现以下错误。 SyntaxError: prefix 'owl' not found in prefix map 我尝试阅读http://effbot.org/zone/element-namespaces.htm上的文档,但由于上述XML具有多个嵌套的名称空间,因此仍然无法正常工作。 请让我知道如何更改代码以查找所有owl:Class标签。

10
如何找到Python函数的参数数量?
如何找到Python函数的参数数量?我需要知道它有多少个普通参数以及多少个命名参数。 例: def someMethod(self, arg1, kwarg1=None): pass 此方法有2个参数和1个命名参数。
163 python  function 

22
如何让PyLint识别numpy成员?
我在Python项目上运行PyLint。PyLint抱怨无法找到numpy成员。在避免跳过成员资格检查的同时如何避免这种情况。 从代码: import numpy as np print np.zeros([1, 4]) 运行时,我得到了预期的结果: [[0. 0. 0. 0.]] 但是,pylint给了我这个错误: E:3,6:模块'numpy'没有'zeros'成员(no-member) 对于版本,我使用的是pylint 1.0.0(星号1.0.1,常见的0.60.0),并尝试使用numpy 1.8.0。
163 python  numpy  pylint 


6
定义Python源代码编码的正确方法
PEP 263定义了如何声明Python源代码编码。 通常,Python文件的前两行应以: #!/usr/bin/python # -*- coding: <encoding name> -*- 但是我看过很多以以下内容开头的文件: #!/usr/bin/python # -*- encoding: <encoding name> -*- => 编码而不是编码。 那么,声明文件编码的正确方法是什么? 是否允许使用编码,因为使用的正则表达式是惰性的?还是仅仅是声明文件编码的另一种形式? 我问这个问题是因为PEP不在谈论编码,它只是在谈论编码。
163 python  encoding 


9
提取numpy数组中的特定列
这是一个简单的问题,但要说我有一个MxN矩阵。我要做的就是提取特定的列并将其存储在另一个numpy数组中,但是我得到了无效的语法错误。这是代码: extractedData = data[[:,1],[:,9]]. 似乎上述行就足够了,但我想不是。我环顾四周,但找不到关于此特定场景的任何语法明智的方法。
163 python  syntax  numpy 

7
Python 2和3之间的numpy数组的Pickle不兼容
我正在尝试使用此程序加载在Python 3.2中链接到此处的MNIST数据集: import pickle import gzip import numpy with gzip.open('mnist.pkl.gz', 'rb') as f: l = list(pickle.load(f)) print(l) 不幸的是,它给了我错误: Traceback (most recent call last): File "mnist.py", line 7, in <module> train_set, valid_set, test_set = pickle.load(f) UnicodeDecodeError: 'ascii' codec can't decode byte 0x90 in position 614: ordinal not in range(128) 然后,我尝试在Python 2.7中解码腌制的文件,然后重新编码。因此,我在Python …

4
使用Matplotlib在Python中绘制时间
我有一个格式为(HH:MM:SS.mmmmmm)的时间戳数组和另一个浮点数数组,每个浮点数对应于timestamp数组中的一个值。 我可以使用Matplotlib在x轴上绘制时间,在y轴上绘制数字吗? 我试图这样做,但是不知何故它只接受浮点数数组。如何获取时间图?我必须以任何方式修改格式吗?
163 python  graph  plot  matplotlib 

6
当您的应用具有测试目录时,在Django中运行特定的测试用例
Django文档(http://docs.djangoproject.com/en/1.3/topics/testing/#running-tests)指出,您可以通过指定单个测试用例来运行它们: $ ./manage.py test animals.AnimalTestCase 假设您将测试保存在Django应用程序的tests.py文件中。如果是这样,那么此命令将按预期工作。 我在tests目录中有针对Django应用程序的测试: my_project/apps/my_app/ ├── __init__.py ├── tests │ ├── __init__.py │ ├── field_tests.py │ ├── storage_tests.py ├── urls.py ├── utils.py └── views.py 该tests/__init__.py文件具有suite()函数: import unittest from my_project.apps.my_app.tests import field_tests, storage_tests def suite(): tests_loader = unittest.TestLoader().loadTestsFromModule test_suites = [] test_suites.append(tests_loader(field_tests)) test_suites.append(tests_loader(storage_tests)) return unittest.TestSuite(test_suites) 要运行测试,请执行以下操作: $ ./manage.py …

9
Python日志记录:使用毫秒格式的时间
默认情况下logging.Formatter('%(asctime)s'),使用以下格式打印: 2011-06-09 10:54:40,638 其中638是毫秒。我需要将逗号更改为点: 2011-06-09 10:54:40.638 要格式化时间,我可以使用: logging.Formatter(fmt='%(asctime)s',datestr=date_format_str) 但是,文档未指定如何设置毫秒格式。我发现这太问题,其中约微秒的会谈,但)我宁愿毫秒和b)下列不上的Python 2.6(其中我的工作),由于工作的关系%f: logging.Formatter(fmt='%(asctime)s',datefmt='%Y-%m-%d,%H:%M:%S.%f')
163 python  logging  time 

10
列表的熊猫列,为每个列表元素创建一行
我有一个数据框,其中某些单元格包含多个值的列表。我不想扩展一个单元格中的多个值,而是想扩展数据框,以便列表中的每个项目都有自己的行(所有其他列中的值都相同)。所以,如果我有: import pandas as pd import numpy as np df = pd.DataFrame( {'trial_num': [1, 2, 3, 1, 2, 3], 'subject': [1, 1, 1, 2, 2, 2], 'samples': [list(np.random.randn(3).round(2)) for i in range(6)] } ) df Out[10]: samples subject trial_num 0 [0.57, -0.83, 1.44] 1 1 1 [-0.01, 1.13, 0.36] 1 …
163 python  pandas  list 

2
从__future__导入absolute_import实际起什么作用?
我已经回答了有关Python中绝对导入的问题,我认为通过阅读Python 2.5 changelog和随附的PEP可以理解。但是,在安装Python 2.5并尝试制作一个正确使用的示例时from __future__ import absolute_import,我意识到事情还不清楚。 直接从上面链接的更改日志,此语句准确总结了我对绝对导入更改的理解: 假设您有一个像这样的包目录: pkg/ pkg/__init__.py pkg/main.py pkg/string.py 这定义了一个名为的包,pkg其中包含pkg.main和pkg.string子模块。 考虑main.py模块中的代码。如果执行该语句会import string怎样?在Python 2.4和更早的版本,它会先看看在包的目录进行相对进口,发现包装/ string.py,进口该文件的内容pkg.string模块,并且该模块被绑定到名字"string"的pkg.main模块的名称空间。 所以我创建了这个确切的目录结构: $ ls -R .: pkg/ ./pkg: __init__.py main.py string.py __init__.py并且string.py是空的。main.py包含以下代码: import string print string.ascii_uppercase 不出所料,使用Python 2.5运行此命令失败,并显示AttributeError: $ python2.5 pkg/main.py Traceback (most recent call last): File "pkg/main.py", line 2, in <module> print …

3
在函数结束(例如,检查失败)之前,在python中退出函数(没有返回值)的最佳方法是什么?
让我们假设一个迭代,其中我们调用一个没有返回值的函数。我认为我的程序应该表现的方式在以下伪代码中进行了解释: for element in some_list: foo(element) def foo(element): do something if check is true: do more (because check was succesful) else: return None do much much more... 如果我在python中实现此功能,则该函数返回一个None。是否有更好的方式“如果在函数主体中检查失败,则退出没有返回值的函数”?
163 python  function  return 

By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.