标签归档:python-3.x

在Python 3中是否可以看到generator.next()?

问题:在Python 3中是否可以看到generator.next()?

我有一个生成序列的生成器,例如:

def triangle_nums():
    '''Generates a series of triangle numbers'''
    tn = 0
    counter = 1
    while True:
        tn += counter
        yield tn
        counter += + 1

在Python 2中,我可以进行以下调用:

g = triangle_nums()  # get the generator
g.next()             # get the next value

但是在Python 3中,如果我执行相同的两行代码,则会出现以下错误:

AttributeError: 'generator' object has no attribute 'next'

但是,循环迭代器语法确实可以在Python 3中使用

for n in triangle_nums():
    if not exit_cond:
       do_something()...

我还没有找到任何可以解释Python 3行为差异的信息。

I have a generator that generates a series, for example:

def triangle_nums():
    '''Generates a series of triangle numbers'''
    tn = 0
    counter = 1
    while True:
        tn += counter
        yield tn
        counter += + 1

In Python 2 I am able to make the following calls:

g = triangle_nums()  # get the generator
g.next()             # get the next value

however in Python 3 if I execute the same two lines of code I get the following error:

AttributeError: 'generator' object has no attribute 'next'

but, the loop iterator syntax does work in Python 3

for n in triangle_nums():
    if not exit_cond:
       do_something()...

I haven’t been able to find anything yet that explains this difference in behavior for Python 3.


回答 0

g.next()已重命名为g.__next__()。这样做的原因是一致性:特殊方法(例如__init__()和)__del__()都带有双下划线(在当前情况下为“ dunder”),并且.next()是该规则的少数exceptions之一。这已在Python 3.0中修复。[*]

但是请不要g.__next__()使用next(g)

[*]还有其他特殊属性可以解决此问题;func_name,现在__name__等等。

g.next() has been renamed to g.__next__(). The reason for this is consistency: special methods like __init__() and __del__() all have double underscores (or “dunder” in the current vernacular), and .next() was one of the few exceptions to that rule. This was fixed in Python 3.0. [*]

But instead of calling g.__next__(), use next(g).

[*] There are other special attributes that have gotten this fix; func_name, is now __name__, etc.


回答 1

尝试:

next(g)

查看这个整洁的表,其中显示了2和3之间的语法差异。

Try:

next(g)

Check out this neat table that shows the differences in syntax between 2 and 3 when it comes to this.


回答 2

如果您的代码必须在Python2和Python3下运行,请使用2to3 六个库,如下所示:

import six

six.next(g)  # on PY2K: 'g.next()' and onPY3K: 'next(g)'

If your code must run under Python2 and Python3, use the 2to3 six library like this:

import six

six.next(g)  # on PY2K: 'g.next()' and onPY3K: 'next(g)'

使用pickle.dump-TypeError:必须为str,而不是字节

问题:使用pickle.dump-TypeError:必须为str,而不是字节

我正在使用python3.3,并且在尝试腌制一个简单的字典时遇到一个神秘的错误。

这是代码:

import os
import pickle
from pickle import *
os.chdir('c:/Python26/progfiles/')

def storvars(vdict):      
    f = open('varstor.txt','w')
    pickle.dump(vdict,f,)
    f.close()
    return

mydict = {'name':'john','gender':'male','age':'45'}
storvars(mydict)

我得到:

Traceback (most recent call last):
  File "C:/Python26/test18.py", line 31, in <module>
    storvars(mydict)
  File "C:/Python26/test18.py", line 14, in storvars
    pickle.dump(vdict,f,)
TypeError: must be str, not bytes

I’m using python3.3 and I’m having a cryptic error when trying to pickle a simple dictionary.

Here is the code:

import os
import pickle
from pickle import *
os.chdir('c:/Python26/progfiles/')

def storvars(vdict):      
    f = open('varstor.txt','w')
    pickle.dump(vdict,f,)
    f.close()
    return

mydict = {'name':'john','gender':'male','age':'45'}
storvars(mydict)

and I get:

Traceback (most recent call last):
  File "C:/Python26/test18.py", line 31, in <module>
    storvars(mydict)
  File "C:/Python26/test18.py", line 14, in storvars
    pickle.dump(vdict,f,)
TypeError: must be str, not bytes

回答 0

需要以二进制模式打开输出文件:

f = open('varstor.txt','w')

需要是:

f = open('varstor.txt','wb')

The output file needs to be opened in binary mode:

f = open('varstor.txt','w')

needs to be:

f = open('varstor.txt','wb')

回答 1

只是有同样的问题。在Python 3中,必须指定二进制模式’wb’,’rb’,而在Python 2x中则不需要。当您遵循基于Python 2x的教程时,这就是您在这里的原因。

import pickle

class MyUser(object):
    def __init__(self,name):
        self.name = name

user = MyUser('Peter')

print("Before serialization: ")
print(user.name)
print("------------")
serialized = pickle.dumps(user)
filename = 'serialized.native'

with open(filename,'wb') as file_object:
    file_object.write(serialized)

with open(filename,'rb') as file_object:
    raw_data = file_object.read()

deserialized = pickle.loads(raw_data)


print("Loading from serialized file: ")
user2 = deserialized
print(user2.name)
print("------------")

Just had same issue. In Python 3, Binary modes ‘wb’, ‘rb’ must be specified whereas in Python 2x, they are not needed. When you follow tutorials that are based on Python 2x, that’s why you are here.

import pickle

class MyUser(object):
    def __init__(self,name):
        self.name = name

user = MyUser('Peter')

print("Before serialization: ")
print(user.name)
print("------------")
serialized = pickle.dumps(user)
filename = 'serialized.native'

with open(filename,'wb') as file_object:
    file_object.write(serialized)

with open(filename,'rb') as file_object:
    raw_data = file_object.read()

deserialized = pickle.loads(raw_data)


print("Loading from serialized file: ")
user2 = deserialized
print(user2.name)
print("------------")

函数参数中仅带有星号?

问题:函数参数中仅带有星号?

函数参数中的星号有什么作用?

当我查看pickle模块时,我看到了:

pickle.dump(obj, file, protocol=None, *, fix_imports=True)

我知道在参数之前(对于可变数量的参数)之前有一个单星号和一个双星号,但是这没有任何前缀。而且我敢肯定,这与泡菜无关。那可能只是这种情况的一个例子。我将其发送给翻译人员时才知道它的名字:

>>> def func(*):
...     pass
...
  File "<stdin>", line 1
SyntaxError: named arguments must follow bare *

如果重要的话,我使用的是python 3.3.0。

What does a bare asterisk in the arguments of a function do?

When I looked at the pickle module, I see this:

pickle.dump(obj, file, protocol=None, *, fix_imports=True)

I know about a single and double asterisks preceding arguments (for variable number of arguments), but this precedes nothing. And I’m pretty sure this has nothing to do with pickle. That’s probably just an example of this happening. I only learned its name when I sent this to the interpreter:

>>> def func(*):
...     pass
...
  File "<stdin>", line 1
SyntaxError: named arguments must follow bare *

If it matters, I’m on python 3.3.0.


回答 0

Bare *用于强制调用者使用命名参数-因此,如果*没有以下关键字参数,则无法将函数定义为参数。

有关更多详细信息,请参见此答案Python 3文档

Bare * is used to force the caller to use named arguments – so you cannot define a function with * as an argument when you have no following keyword arguments.

See this answer or Python 3 documentation for more details.


回答 1

当原始答案完全回答问题时,只需添加一些相关信息即可。单个星号的行为源自PEP-3102。引用相关部分:

The second syntactical change is to allow the argument name to
be omitted for a varargs argument. The meaning of this is to
allow for keyword-only arguments for functions that would not
otherwise take a varargs argument:

    def compare(a, b, *, key=None):
        ...

简单来说,这意味着要传递key的值,您需要将其显式传递为key="value"

While the original answer answers the question completely, just adding a bit of related information. The behaviour for the single asterisk derives from PEP-3102. Quoting the related section:

The second syntactical change is to allow the argument name to
be omitted for a varargs argument. The meaning of this is to
allow for keyword-only arguments for functions that would not
otherwise take a varargs argument:

    def compare(a, b, *, key=None):
        ...

In simple english, it means that to pass the value for key, you will need to explicitly pass it as key="value".


回答 2

def func(*, a, b):
    print(a)
    print(b)

func("gg") # TypeError: func() takes 0 positional arguments but 1 was given
func(a="gg") # TypeError: func() missing 1 required keyword-only argument: 'b'
func(a="aa", b="bb", c="cc") # TypeError: func() got an unexpected keyword argument 'c'
func(a="aa", b="bb", "cc") # SyntaxError: positional argument follows keyword argument
func(a="aa", b="bb") # aa, bb

上面带有** kwargs的示例

def func(*, a, b, **kwargs):
    print(a)
    print(b)
    print(kwargs)

func(a="aa",b="bb", c="cc") # aa, bb, {'c': 'cc'}
def func(*, a, b):
    print(a)
    print(b)

func("gg") # TypeError: func() takes 0 positional arguments but 1 was given
func(a="gg") # TypeError: func() missing 1 required keyword-only argument: 'b'
func(a="aa", b="bb", c="cc") # TypeError: func() got an unexpected keyword argument 'c'
func(a="aa", b="bb", "cc") # SyntaxError: positional argument follows keyword argument
func(a="aa", b="bb") # aa, bb

the above example with **kwargs

def func(*, a, b, **kwargs):
    print(a)
    print(b)
    print(kwargs)

func(a="aa",b="bb", c="cc") # aa, bb, {'c': 'cc'}

回答 3

从语义上讲,这意味着其后的参数仅是关键字,因此,如果尝试在不指定名称的情况下提供参数,则会出现错误。例如:

>>> def f(a, *, b):
...     return a + b
...
>>> f(1, 2)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: f() takes 1 positional argument but 2 were given
>>> f(1, b=2)
3

在实用上,这意味着您必须使用关键字参数来调用该函数。如果在没有参数名称给出提示的情况下很难理解参数的目的,通常会这样做。

比较例如sorted(nums, reverse=True)vs.如果您写过sorted(nums, True)。后者的可读性要差得多,因此Python开发人员选择让您以前一种方式编写它。

Semantically, it means the arguments following it are keyword-only, so you will get an error if you try to provide an argument without specifying its name. For example:

>>> def f(a, *, b):
...     return a + b
...
>>> f(1, 2)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: f() takes 1 positional argument but 2 were given
>>> f(1, b=2)
3

Pragmatically, it means you have to call the function with a keyword argument. It’s usually done when it would be hard to understand the purpose of the argument without the hint given by the argument’s name.

Compare e.g. sorted(nums, reverse=True) vs. if you wrote sorted(nums, True). The latter would be much less readable, so the Python developers chose to make you to write it the former way.


回答 4

假设您具有以下功能:

def sum(a,key=5):
    return a + key 

您可以通过两种方式调用此函数:

sum(1,2) 要么 sum(1,key=2)

假设您只想sum使用关键字参数来调用函数。

您添加*到函数参数列表以标记位置参数的结尾。

所以函数定义为:

def sum(a,*,key=5):
    return a + key 

只能使用 sum(1,key=2)

Suppose you have function:

def sum(a,key=5):
    return a + key 

You can call this function in 2 ways:

sum(1,2) or sum(1,key=2)

Suppose you want function sum to be called only using keyword arguments.

You add * to the function parameter list to mark the end of positional arguments.

So function defined as:

def sum(a,*,key=5):
    return a + key 

may be called only using sum(1,key=2)


回答 5

我发现下面的链接,是非常有益的解释**args以及**kwargs

https://pythontips.com/2013/08/04/args-and-kwargs-in-python-explained/

本质上,除了上面的答案之外,我还从上面的网站(信用:https : //pythontips.com/author/yasoob008/)学到了以下内容:

在下面首先定义演示功能的情况下,有两个示例,一个带有*args和一个带有**kwargs

def test_args_kwargs(arg1, arg2, arg3):
    print "arg1:", arg1
    print "arg2:", arg2
    print "arg3:", arg3

# first with *args
>>> args = ("two", 3,5)
>>> test_args_kwargs(*args)
arg1: two
arg2: 3
arg3: 5

# now with **kwargs:
>>> kwargs = {"arg3": 3, "arg2": "two","arg1":5}
>>> test_args_kwargs(**kwargs)
arg1: 5
arg2: two
arg3: 3

因此*args,您可以动态建立一个参数列表,该参数列表将按照其输入的顺序进行处理,而**kwargs可以启用NAMED参数的传递,并且可以由NAME进行相应的处理(而与它们的输入顺序无关) 。

该站点继续,并指出参数的正确顺序应为:

some_func(fargs,*args,**kwargs)

I’ve found the following link to be very helpful explaining *, *args and **kwargs:

https://pythontips.com/2013/08/04/args-and-kwargs-in-python-explained/

Essentially, in addition to the answers above, I’ve learned from the site above (credit: https://pythontips.com/author/yasoob008/) the following:

With the demonstration function defined first below, there are two examples, one with *args and one with **kwargs

def test_args_kwargs(arg1, arg2, arg3):
    print "arg1:", arg1
    print "arg2:", arg2
    print "arg3:", arg3

# first with *args
>>> args = ("two", 3,5)
>>> test_args_kwargs(*args)
arg1: two
arg2: 3
arg3: 5

# now with **kwargs:
>>> kwargs = {"arg3": 3, "arg2": "two","arg1":5}
>>> test_args_kwargs(**kwargs)
arg1: 5
arg2: two
arg3: 3

So *args allows you to dynamically build a list of arguments that will be taken in the order in which they are fed, whereas **kwargs can enable the passing of NAMED arguments, and can be processed by NAME accordingly (irrespective of the order in which they are fed).

The site continues, noting that the correct ordering of arguments should be:

some_func(fargs,*args,**kwargs)

需要Microsoft Visual C ++ 14.0(无法找到vcvarsall.bat)

问题:需要Microsoft Visual C ++ 14.0(无法找到vcvarsall.bat)

我已经安装了Python 3.5,并且在运行时

pip install mysql-python

它给我以下错误

error: Microsoft Visual C++ 14.0 is required (Unable to find vcvarsall.bat)

我在“路径”中添加了以下几行

C:\Program Files\Python 3.5\Scripts\;
C:\Program Files\Python 3.5\;

C:\Windows\System32;
C:\Program Files (x86)\Microsoft Visual Studio 12.0\VC;
C:\Program Files (x86)\Microsoft Visual Studio 11.0\VC

我的PC上安装了64位win 7。

有什么能减轻这个错误,并通过正确地安装模块的解决方案pip

I’ve installed Python 3.5 and while running

pip install mysql-python

it gives me the following error

error: Microsoft Visual C++ 14.0 is required (Unable to find vcvarsall.bat)

I have added the following lines to my Path

C:\Program Files\Python 3.5\Scripts\;
C:\Program Files\Python 3.5\;

C:\Windows\System32;
C:\Program Files (x86)\Microsoft Visual Studio 12.0\VC;
C:\Program Files (x86)\Microsoft Visual Studio 11.0\VC

I have a 64bit win 7 setup in my PC.

What could be the solution for mitigating this error and installing the modules correctly via pip.


回答 0

您的路径仅列出Visual Studio 11和12,需要14,即Visual Studio 2015。如果您安装了该程序,并记住勾选该复选框,Languages->C++那么它应该可以工作。

在我的Python 3.5安装中,错误消息有用得多,并且包含从中获取错误消息的URL。

 error: Microsoft Visual C++ 14.0 is required. Get it with "Microsoft Visual C++ Build Tools": http://landinghub.visualstudio.com/visual-cpp-build-tools

编辑:新的工作链接

编辑:根据Lightfire228的建议,您可能还需要升级setuptools软件包以使错误消失:

pip install --upgrade setuptools

Your path only lists Visual Studio 11 and 12, it wants 14, which is Visual Studio 2015. If you install that, and remember to tick the box for Languages->C++ then it should work.

On my Python 3.5 install, the error message was a little more useful, and included the URL to get it from

 error: Microsoft Visual C++ 14.0 is required. Get it with "Microsoft Visual C++ Build Tools": http://landinghub.visualstudio.com/visual-cpp-build-tools

Edit: New working link

Edit: As suggested by Lightfire228, you may also need to upgrade setuptools package for the error to disappear:

pip install --upgrade setuptools

回答 1

二进制安装它的简单方法!

我不敢相信没有人建议过-对pip使用仅二进制选项。例如,对于mysqlclient:

pip install --only-binary :all: mysqlclient

许多软件包不会为每个发行版创建构建,这会迫使您的点子从源代码构建。如果您愿意使用最新的预编译二进制版本,请使用--only-binary :all:允许pip使用较旧的二进制版本。

Binary install it the simple way!

I can’t believe no one has suggested this already – use the binary-only option for pip. For example, for mysqlclient:

pip install --only-binary :all: mysqlclient

Many packages don’t create a build for every single release which forces your pip to build from source. If you’re happy to use the latest pre-compiled binary version, use --only-binary :all: to allow pip to use an older binary version.


回答 2

解决以下任何错误:

  • Failed building wheel for misaka
  • Failed to build misaka
  • Microsoft Visual C++ 14.0 is required
  • Unable to find vcvarsall.bat

解决方案是:

  1. 转到Visual Studio 2017的构建工具

  2. 在Visual Studio Community 2017下选择免费下载。这将下载安装程序。运行安装程序。

  3. 在“工作负载”选项卡下选择所需的内容:

    一个。在Windows下,有3个选择。仅使用C ++检查桌面开发

    b。在“ Web&Cloud”下,有7个选择。仅检查Python开发(我相信这是可选的,但我已经做到了)。

  4. 在cmd中输入 pip3 install misaka

请注意,如果您已经安装了Visual Studio,则在运行安装程序时可以修改您的安装程序(在Visual Studio Community 2017下单击“修改”按钮)并执行步骤3和4

最后的注意事项:如果您不想安装所有模块,那么拥有下面的3个模块(或VC ++ 2017的较新版本)就足够了。(您也可以仅使用这些选项来安装Visual Studio Build Tools,因此您不需要安装Visual Studio Community Edition本身)=>此最小安装已经是4.5GB,因此保存所有内容都会有所帮助

To solve any of the following errors:

  • Failed building wheel for misaka
  • Failed to build misaka
  • Microsoft Visual C++ 14.0 is required
  • Unable to find vcvarsall.bat

The Solution is:

  1. Go to Build Tools for Visual Studio 2017

  2. Select free download under Visual Studio Community 2017. This will download the installer. Run the installer.

  3. Select what you need under workload tab:

    a. Under Windows, there are 3 choices. Only check Desktop development with C++

    b. Under Web & Cloud, there are 7 choices. Only check Python development (I believe this is optional But I have done it).

  4. In cmd, type pip3 install misaka

Note if you already installed Visual Studio then when you run the installer, you can modify yours (click modify button under Visual Studio Community 2017) and do steps 3 and 4

Final Note : If you don’t want to install all modules, having the 3 ones below (or a newer version of the VC++ 2017) would be sufficient. (you can also install the Visual Studio Build Tools with only these options so you dont need to install Visual Studio Community Edition itself) => This minimal install is already a 4.5GB, so saving off anything is helpful


回答 3

正如其他答复所指出的那样,一种解决方案是安装Visual Studio2015。但是,这需要几个GB的磁盘空间。一种解决方法是安装预编译的二进制文件。该网页http://www.lfd.uci.edu/~gohlke/pythonlibs)包含预编译的二进制许多Python包。下载感兴趣的包你之后,你可以使用安装pip install,例如pip install mysqlclient‑1.3.10‑cp35‑cp35m‑win_amd64.whl

As the other responses pointed out, one solution is to install Visual Studio 2015. However, it takes a few GBs of disk space. One way around is to install precompiled binaries. The webpage http://www.lfd.uci.edu/~gohlke/pythonlibs (mirror) contains precompiled binaries for many Python packages. After downloading the package of interest to you, you can install it using pip install, e.g. pip install mysqlclient‑1.3.10‑cp35‑cp35m‑win_amd64.whl.


回答 4

尝试在Windows 10计算机上安装Scrapy Web抓取Python框架时遇到了确切的问题。我这样想出了解决方案:

  1. 从此链接下载最新的(最后一个)车轮文件👉 扭曲包装的车轮文件

  2. 我建议将该滚轮文件保存在您安装Python的目录中,即本地磁盘C中的某个位置

  3. 然后访问wheel文件所在的文件夹并运行pip install <*wheel file's name*>

  4. 最后pip install Scrapy再次运行该命令,可以很好地使用Scrapy或其他任何需要下载大量Windows C ++ Package / SDK的工具

免责声明:此解决方案在尝试安装Scrapy时对我有用,但我不能保证在安装其他软件/软件包/等时也会发生这种情况。

I had the exact issue while trying to install Scrapy web scraping Python framework on my Windows 10 machine. I figured out the solution this way:

  1. Download the latest (the last one) wheel file from this link 👉 wheel file for twisted package

  2. I’d recommend saving that wheel file in the directory where you’ve installed Python i.e somewhere in Local Disk C

  3. Then visit the folder where the wheel file exists and run pip install <*wheel file's name*>

  4. Finally run the command pip install Scrapy again and you’re good to use Scrapy or any other tool which required you to download massive Windows C++ Package/SDK.

Disclaimer: This solution worked for me while trying to install Scrapy, but I can’t guarantee the same happening while installing other softwares/packages/etc.✌


回答 5

我在尝试安装时遇到了这个确切的问题mayavi

因此,error: Microsoft Visual C++ 14.0 is required在安装库时,我也有共同点。

寻找在许多网页和解决方案,这个线程,与后没有他们的工作的。我认为这些步骤(大部分是从以前的解决方案中提取的)使它可以正常工作。

  1. 转到Visual Studio 2017的构建工具并安装Build Tools for Visual Studio 2017。下All downloads向下滚动)>>Tools for Visual Studio 2017
    • 如果已经安装,请跳至2

  1. 选择C++ Components您需要的(我不知道我需要哪个,所以安装了许多)。
    • 如果已经安装,Build Tools for Visual Studio 2017则打开应用程序,Visual Studio Installer然后转到Visual Studio Build Tools 2017>> Modify>>,Individual Components然后选择所需的组件。
    • 从其他的答案中的重要组成部分似乎是:C++/CLI supportVC++ 2017 version <...> latestVisual C++ 2017 Redistributable UpdateVisual C++ tools for CMakeWindows 10 SDK <...> for Desktop C++Visual C++ Build Tools core featuresVisual Studio C++ core features

  1. 为安装/修改这些组件Visual Studio Build Tools 2017

  2. 这是重要的一步。打开应用程序,Visual Studio Installer然后转到Visual Studio Build Tools>> Launch。这将在正确的位置打开CMD窗口Microsoft Visual Studio\YYYY\BuildTools

  1. 现在,python -m pip install --upgrade setuptools在此CMD窗口中输入。

  1. 最后,在同一 CMD窗口pip中安装python库:pip install -U <library>

I had this exact issue while trying to install mayavi.

So I also had the common error: Microsoft Visual C++ 14.0 is required when pip installing a library.

After looking across many web pages and the solutions to this thread, with none of them working. I figured these steps (most taken from previous solutions) allowed this to work.

  1. Go to Build Tools for Visual Studio 2017 and install Build Tools for Visual Studio 2017. Which is under All downloads (scroll down) >> Tools for Visual Studio 2017
    • If you have already installed this skip to 2.

  1. Select the C++ Components you require (I didn’t know which I required so installed many of them).
    • If you have already installed Build Tools for Visual Studio 2017 then open the application Visual Studio Installer then go to Visual Studio Build Tools 2017 >> Modify >> Individual Components and selected the required components.
    • From other answers important components appear to be: C++/CLI support, VC++ 2017 version <...> latest, Visual C++ 2017 Redistributable Update, Visual C++ tools for CMake, Windows 10 SDK <...> for Desktop C++, Visual C++ Build Tools core features, Visual Studio C++ core features.

  1. Install/Modify these components for Visual Studio Build Tools 2017.

  2. This is the important step. Open the application Visual Studio Installer then go to Visual Studio Build Tools >> Launch. Which will open a CMD window at the correct location for Microsoft Visual Studio\YYYY\BuildTools.

  1. Now enter python -m pip install --upgrade setuptools within this CMD window.

  1. Finally, in this same CMD window pip install your python library: pip install -U <library>.


回答 6

安装spaCy模块时遇到相同的问题。我检查了控制面板,我已经安装了几个可视的C ++可再发行组件。

我所做的是选择已经安装在我的PC上的“ Microsoft Visual Studio Community 2015”->“修改”->选中“ Visual C ++ 2015通用工具”。然后,将花费一些时间并下载超过1 GB的空间进行安装。

这解决了我的问题。现在,我已经安装了spaCy。

I had the same problem when installing spaCy module. And I checked control panel I have several visual C++ redistributables installed already.

What I did was select “Microsoft Visual Studio Community 2015” which is already installed on my PC –> “Modify” –>check “Common Tools for Visual C++ 2015”. Then it will take some time and download more than 1 GB to install it.

This fixed my issue. Now I have spaCy installed.


回答 7

我有同样的问题。更新设置工具的解决方案

pip install -U setuptools

要么

pip install setuptools --upgrade

I had this same problem. A solution for updating setuptools

pip install -U setuptools

or

pip install setuptools --upgrade

回答 8

在阅读了SO中的很多答案并且没有一个有效的方法之后,我终于设法按照线程中的步骤解决了这个问题,如果页面消失了,我将在这里保留这些步骤:

请尝试安装用于Visual Studio 2017的构建工具,选择工作负载“ Visual C ++生成工具”,然后检查选项“ C ++ / CLI支持”和“用于桌面的VC ++ 2015.3 v14.00(v140)工具集”,如下所示。

希望它对我有帮助。

After reading a lot of answers in SO and none of them working, I finally managed to solve it following the steps in this thread, I will leave here the steps in case the page dissapears:

Please try to install Build Tools for Visual Studio 2017, select the workload “Visual C++ build tools” and check the options “C++/CLI support” and “VC++ 2015.3 v14.00 (v140) toolset for desktop” as below.

Hope it helps as it did for me.


回答 9

确保您已经安装了这些必需的软件包。在我安装已检查的软件包的情况下,可以正常工作

Make sure that you’ve installed these required packages.Worked perfectly in my case as i installed the checked packages


回答 10

为了扩展ocean800davidsheldonuser3661384的答案:

现在,您应该不再使用Visual Studio Tools 2015,因为已有新版本可用。如Python文档所述,您应该改用Visual Studio Tools 2017。

Microsoft已将Visual C ++生成工具2015升级为Visual Studio 2017的生成工具。

这里下载

setuptools如果您没有运行安装工具,则还需要:

pip install setuptools

或者,如果您已经拥有它,请确保对其进行升级。

pip install setuptools --upgrade

对于上面的Python文档链接,您将看到setuptools版本必须至少为34.4.0。为VS工具工作

To expand on the answers by ocean800, davidsheldon and user3661384:

You should now no longer use Visual Studio Tools 2015 since a newer version is available. As indicated by the Python documentation you should be using Visual Studio Tools 2017 instead.

Visual C++ Build Tools 2015 was upgraded by Microsoft to Build Tools for Visual Studio 2017.

Download it from here

You will require also need setuptools, if you don’t have setup tools run:

pip install setuptools

Or if you already have it, be sure to upgrade it.

pip install setuptools --upgrade

For the Python documentation link above you will see that setuptools version must be at least 34.4.0. for VS Tools to work


回答 11

使用此链接下载和安装Visual C ++ 2015生成工具。它会自动下载visualcppbuildtools_full.exe并安装Visual C ++ 14.0,而无需实际安装Visual Studio。安装完成后,重试pip安装,您将不会再收到错误消息。

我已经在以下平台和版本上对其进行了测试:

Python 3.6 on Windows 7 64-bit
Python 3.8 on Windows 10 64-bit

我对这个问题的评论与我有相同的建议,但是,我被要求将其发布为答案,因为它对很多人都有帮助。因此,我将其发布为答案。

Use this link to download and install Visual C++ 2015 Build Tools. It will automatically download visualcppbuildtools_full.exe and install Visual C++ 14.0 without actually installing Visual Studio. After the installation completes, retry pip install and you won’t get the error again.

I have tested it on following platform and versions:

Python 3.6 on Windows 7 64-bit
Python 3.8 on Windows 10 64-bit

I have same suggestion as a comment to the question, however, I have been requested to post this as an answer as it helped a lot of people. So I posted it as an answer.


回答 12

我有完全相同的问题,并通过安装mysql-connector-python来解决:

pip install mysql-connector-python

我是在python3.7和Windows 10安装Microsoft构建工具为Visual Studio 2017年(描述这里)没有解决我的问题,这是等同于你的。

I had exactly the same issue and solved it by installing mysql-connector-python with:

pip install mysql-connector-python

I am on python3.7 & windows 10 and installing Microsoft Build Tools for Visual Studio 2017 (as described here) did not solve my problem that was identical to yours.


回答 13

我遇到过同样的问题。下载适用于Visual Studio 2017的构建工具对我有用。在这里找到

I had the same issue. Downloading the Build Tools for Visual Studio 2017 worked for me. Find it here


回答 14

使用链接到Visual C ++ 2015生成工具。这将安装Visual C ++ 14.0,而无需安装Visual Studio。

Use the link to Visual C++ 2015 Build Tools. That will install Visual C++ 14.0 without installing Visual Studio.


回答 15

在使用最新的Python 3.6时遇到了同样的问题。使用Windows OS 10家庭版和64位操作系统

解决此问题的步骤:

  1. 通过控制面板卸载您拥有的任何版本的Visual Studio
  2. 安装Visual Studio 2015并选择默认选项,该选项将自行安装Visual C ++ 14.0
  3. 您可以使用Pycharm安装scrapy-> Project-> Project Interpreter-> +(安装scrapy)
  4. 通过导入检查REPL和pycharm中的scrapy,您应该不会看到任何错误

Just had the same issue while using the latest Python 3.6. With Windows OS 10 Home Edition and 64 Bit Operation System

Steps to solve this issue :

  1. Uninstall any versions of Visual studio you have had, through Control Panel
  2. Install Visual Studio 2015 and chose the default option that will install Visual C++ 14.0 on its own
  3. You can use Pycharm for installing scrapy ->Project->Project Interpreter->+ (install scrapy)
  4. check scrapy in REPL and pycharm by import , you should not see any errors

回答 16

安装pymssql时遇到类似情况

pip试图构建该软件包,因为没有
适用于python 3.6和Windows的官方轮子。

通过从此处下载非官方的轮子解决了该问题:http://www.lfd.uci.edu/~gohlke/pythonlibs/

专门针对您的情况-> http://www.lfd.uci.edu/~gohlke/pythonlibs/#mysql-python

had a similar situation installing pymssql

pip was trying to build the package because there were no official wheels
for python 3.6 & windows.

solved it by downloading an unoffical wheel from here:
http://www.lfd.uci.edu/~gohlke/pythonlibs/

specifically for your case -> http://www.lfd.uci.edu/~gohlke/pythonlibs/#mysql-python


回答 17

我有同样的问题。我需要一个64位版本的Python,所以我安装了3.5.0(是撰写本文时的最新版本)。切换到3.4.3后,我所有的模块安装均正常。

适用于Windows的Python版本

I had the same problem. I needed a 64-bit version of Python so I installed 3.5.0 (the most recent as of writing this). After switching to 3.4.3 all of my module installations worked.

Python Releases for Windows


回答 18

这里和其他地方的解决方案都不适合我。原来在我的64位Windows 10操作系统上安装了不兼容的32位mysqlclient版本,因为我使用的是32位版本的Python

我必须卸载当前的Python 3.7 32bit,然后重新安装Python 3.7 64bit,现在一切正常

None of the solutions here and elsewhere worked for me. Turns out an incompatible 32bit version of mysqlclient is being installed on my 64bit Windows 10 OS because I’m using a 32bit version of Python

I had to uninstall my current Python 3.7 32bit, and reinstalled Python 3.7 64bit and everything is working fine now


回答 19

查看包装是否有包含必要双轮的正式前叉

我需要该软件包python-Levenshtein,发生此错误,然后找到该软件包python-Levenshtein-wheels

Look if the package have an official fork that include the necessary binary wheels.

I needed the package python-Levenshtein, had this error, and find the package python-Levenshtein-wheels instead.


回答 20

只需转到https://www.lfd.uci.edu/~gohlke/pythonlibs/找到合适的软件包(whl文件)。下载它。转到cmd中的下载文件夹,或在文件夹的地址栏上键入“ cmd”。运行命令:

pip install mysqlclient-1.4.6-cp38-cp38-win32.whl

(正确输入文件名。我仅给出一个示例)。您的问题将得到解决,而无需安装6GB大小的构建收费cpp。

Just go to https://www.lfd.uci.edu/~gohlke/pythonlibs/ find your suitable package (whl file). Download it. Go to the download folder in cmd or typing ‘cmd’ on the address bar of the folder. Run the command :

pip install mysqlclient-1.4.6-cp38-cp38-win32.whl

(Type the file name correctly. I have given an example only). Your problem will be solved without installing build toll cpp of 6GB size.


回答 21

在@Sushant Chaudhary的答案之上添加

就我而言,我又遇到了有关lxml的另一个错误,如下所示

copying src\lxml\isoschematron\resources\xsl\iso-schematron-xslt1\readme.txt -> build\lib.win-amd64-3.7\lxml\isoschematron\resources\xsl\iso-schematron-xslt1
running build_ext
building 'lxml.etree' extension
error: Microsoft Visual C++ 14.0 is required. Get it with "Microsoft Visual C++ Build Tools": http://landinghub.visualstudio.com/visual-cpp-build-tools

我必须以与@Sushant Chaudhary回答相同的方式安装lxml‑4.2.3‑cp37‑cp37m‑win_amd64.whl,才能成功完成Scrapy的安装。

  1. https://www.lfd.uci.edu/~gohlke/pythonlibs/#lxml下载lxml‑4.2.3‑cp37‑cp37m‑win_amd64.whl
  2. 将其放在安装了python的文件夹中
  3. 使用安装 pip install <file-name>

现在您可以运行 pip install scrapy

to add on top of @Sushant Chaudhary’s answer

in my case, I got another error regarding lxml as below

copying src\lxml\isoschematron\resources\xsl\iso-schematron-xslt1\readme.txt -> build\lib.win-amd64-3.7\lxml\isoschematron\resources\xsl\iso-schematron-xslt1
running build_ext
building 'lxml.etree' extension
error: Microsoft Visual C++ 14.0 is required. Get it with "Microsoft Visual C++ Build Tools": http://landinghub.visualstudio.com/visual-cpp-build-tools

I had to install lxml‑4.2.3‑cp37‑cp37m‑win_amd64.whl same way as in the answer of @Sushant Chaudhary to successfully complete installation of Scrapy.

  1. Download lxml‑4.2.3‑cp37‑cp37m‑win_amd64.whl from https://www.lfd.uci.edu/~gohlke/pythonlibs/#lxml
  2. put it in folder where python is installed
  3. install it using pip install <file-name>

now you can run pip install scrapy


回答 22

糟糕!看起来他们在PyPI上没有Windows轮子。

同时,从源代码进行安装可能会起作用,或者尝试按照错误消息中的建议以及此页面上的其他人下载MSVC ++ 14。

Christoph的站点还具有用于Python扩展包(.whl文件)的非官方Windows二进制文件。

请按照以下链接中提到的步骤安装二进制文件:

  1. 直接在基本python中
  2. 在虚拟环境/ Pycharm中

还要检查:

要下载哪个二进制文件?

Oops! Looks like they don’t have Windows wheels on PyPI.

In the meantime, installing from source probably works or try downloading MSVC++ 14 as suggested in the error message and by others on this page.

Christoph’s site also has unofficial Windows Binaries for Python Extension Packages (.whl files).

Follow steps mentioned in following links to install binaries :

  1. Directly in base python
  2. In virtual environments / Pycharm

Also check :

Which binary to download??


回答 23

适用于Python 3.7.4的以下命令集有效:在执行这些命令之前,您需要确认Visual Studio中已安装C ++桌面和Python。

cd "C:\Program Files (x86)\Microsoft Visual Studio\2017\Community\VC\Auxiliary\Build"
vcvarsall.bat x86_amd64
cd \
set CL=-FI"%VCINSTALLDIR%\tools\msvc\14.16.27023\include\stdint.h"


pip install pycrypto

for Python 3.7.4 following set of commands worked: Before those command, you need to confirm Desktop with C++ and Python is installed in Visual Studio.

cd "C:\Program Files (x86)\Microsoft Visual Studio\2017\Community\VC\Auxiliary\Build"
vcvarsall.bat x86_amd64
cd \
set CL=-FI"%VCINSTALLDIR%\tools\msvc\14.16.27023\include\stdint.h"


pip install pycrypto

回答 24

我在安装时遇到了同样的问题 mysqlclient为Django项目。

就我而言,这是导致问题的系统架构不匹配。我的系统上有Windows 7 64位版本。但是,我已经安装了Python 3.7.2 32错误地位版本。

因此,我重新安装了Python解释器(64位)并运行了命令

pip install mysqlclient

我希望这也可以与其他Python包一起使用。

I had the same issue while installing mysqlclient for the Django project.

In my case, it’s the system architecture mismatch causing the issue. I have Windows 7 64bit version on my system. But, I had installed Python 3.7.2 32 bit version by mistake.

So, I re-installed Python interpreter (64bit) and ran the command

pip install mysqlclient

I hope this would work with other Python packages as well.


回答 25

我在Windows 10 python版本3.8上遇到了完全相同的问题。就我而言,我需要在发生错误时安装mysqlclientMicrosoft Visual C++ 14.0 is required。因为安装Visual Studio及其软件包可能是一个乏味的过程,所以我做了以下工作:

第1步-从任何浏览器转到非官方python二进制文件并打开其网站。

第2步-按ctrl + F并输入您想要的任何内容。以我为例,它是mysqlclient。

第3步-进入它,然后根据您的python版本和Windows系统进行选择。就我而言,它是mysqlclient-1.4.6-cp38-cp38-win32.whl并下载。

第4步-打开命令提示符,并指定下载文件的路径。就我而言,它是C:\ Users \ user \ Downloads

步骤5-输入pip install .\mysqlclient‑1.4.6‑cp38‑cp38‑win32.whl并按Enter。

这样就成功安装了它,然后我去了项目终端,重新输入了所需的命令。这解决了我的问题

请注意,在pycharm中处理项目时,我还尝试从项目解释器安装mysql-client。但是mysql-client和mysqlclient是不同的东西。我不知道为什么,它不起作用。

I had the same exact issue on my windows 10 python version 3.8. In my case, I needed to install mysqlclient were the error occurred Microsoft Visual C++ 14.0 is required. Because installing visual studio and it’s packages could be a tedious process, Here’s what I did:

step 1 – Go to unofficial python binaries from any browser and open its website.

step 2 – press ctrl+F and type whatever you want. In my case it was mysqlclient.

step 3 – Go into it and choose according to your python version and windows system. In my case it was mysqlclient‑1.4.6‑cp38‑cp38‑win32.whl and download it.

step 4 – open command prompt and specify the path where you downloaded your file. In my case it was C:\Users\user\Downloads

step 5 – type pip install .\mysqlclient‑1.4.6‑cp38‑cp38‑win32.whl and press enter.

Thus it was installed successfully, after which I went my project terminal re-entered the required command. This solved my problem

Note that, while working on the project in pycharm, I also tried installing mysql-client from the project interpreter. But mysql-client and mysqlclient are different things. I have no idea why and it did not work.


回答 26

我面临着同样的问题。以下对我有用:根据系统上安装的python版本,从Christoph Gohlke安装程序站点下载非官方的二进制文件。导航到已安装文件的文件夹并运行

pip install filename

对我来说python_ldap‑3.0.0‑cp35‑cp35m‑win_amd64.whl,我的机器是64位,而python版本是3.5。这成功在我的Windows机器上安装了python-ldap。您可以为mysql-python尝试相同的操作

I was facing the same problem. The following worked for me: Download the unoffical binaries file from Christoph Gohlke installers site as per the python version installed on your system. Navigate to the folder where you have installed the file and run

pip install filename

For me python_ldap‑3.0.0‑cp35‑cp35m‑win_amd64.whl worked as my machine is 64 bit and python version is 3.5. This successfully installed python-ldap on my windows machine. You can try the same for mysql-python


回答 27

对我来说这工作
pip install –only-binary:all:mysqlclient

This works for me:
pip install --only-binary :all: mysqlclient


回答 28

如果Visual Studio的不是你的东西,而是你正在使用VS代码,那么这个链接会引导你通安装程序来获得C ++在你的Windows上运行。

您只需要完成先决条件部分。 https://code.visualstudio.com/docs/cpp/config-msvc/#_prerequisites

这与其他答案类似,但是此链接的年龄可能会比此处的某些答案更好。

PS:别忘了跑步 pip install --upgrade setuptools

If Visual Studio is NOT your thing, and instead you are using VS Code, then this link will guide you thru the installer to get C++ running on your Windows.

You only needs to complete the Pre-Requisites part. https://code.visualstudio.com/docs/cpp/config-msvc/#_prerequisites

This is similar with other answers, but this link will probably age better than some of the responses here.

PS: don’t forget to run pip install --upgrade setuptools


在Python 3中将字节转换为十六进制字符串的正确方法是什么?

问题:在Python 3中将字节转换为十六进制字符串的正确方法是什么?

在Python 3中将字节转换为十六进制字符串的正确方法是什么?

我看到了bytes.hex方法,bytes.decode编解码器的声明,并尝试了其他最小惊讶的可能功能,但没有用。我只希望字节为十六进制!

What’s the correct way to convert bytes to a hex string in Python 3?

I see claims of a bytes.hex method, bytes.decode codecs, and have tried other possible functions of least astonishment without avail. I just want my bytes as hex!


回答 0

从Python 3.5开始,这终于不再笨拙了:

>>> b'\xde\xad\xbe\xef'.hex()
'deadbeef'

并反向:

>>> bytes.fromhex('deadbeef')
b'\xde\xad\xbe\xef'

也适用于可变bytearray类型。

参考:https : //docs.python.org/3/library/stdtypes.html#bytes.hex

Since Python 3.5 this is finally no longer awkward:

>>> b'\xde\xad\xbe\xef'.hex()
'deadbeef'

and reverse:

>>> bytes.fromhex('deadbeef')
b'\xde\xad\xbe\xef'

works also with the mutable bytearray type.

Reference: https://docs.python.org/3/library/stdtypes.html#bytes.hex


回答 1

使用binascii模块:

>>> import binascii
>>> binascii.hexlify('foo'.encode('utf8'))
b'666f6f'
>>> binascii.unhexlify(_).decode('utf8')
'foo'

查看此答案: Python 3.1.1字符串转换为十六进制

Use the binascii module:

>>> import binascii
>>> binascii.hexlify('foo'.encode('utf8'))
b'666f6f'
>>> binascii.unhexlify(_).decode('utf8')
'foo'

See this answer: Python 3.1.1 string to hex


回答 2

Python具有逐个字节的标准编解码器,可以执行方便的转换,例如带引号的可打印(适合7位ascii),base64(适合字母数字),十六进制转义,gzip和bz2压缩。在Python 2中,您可以执行以下操作:

b'foo'.encode('hex')

在Python 3中,str.encode/ bytes.decode严格用于字节<-> str转换。相反,您可以执行此操作,该操作适用于Python 2和Python 3(反之为s / encode / decode / g):

import codecs
codecs.getencoder('hex')(b'foo')[0]

从Python 3.4开始,有一个不太尴尬的选项:

codecs.encode(b'foo', 'hex')

这些杂项编解码器也可以在它们自己的模块(base64,zlib,bz2,uu,quopri,binascii)中访问;API的一致性较差,但对于压缩编解码器,它提供了更多控制权。

Python has bytes-to-bytes standard codecs that perform convenient transformations like quoted-printable (fits into 7bits ascii), base64 (fits into alphanumerics), hex escaping, gzip and bz2 compression. In Python 2, you could do:

b'foo'.encode('hex')

In Python 3, str.encode / bytes.decode are strictly for bytes<->str conversions. Instead, you can do this, which works across Python 2 and Python 3 (s/encode/decode/g for the inverse):

import codecs
codecs.getencoder('hex')(b'foo')[0]

Starting with Python 3.4, there is a less awkward option:

codecs.encode(b'foo', 'hex')

These misc codecs are also accessible inside their own modules (base64, zlib, bz2, uu, quopri, binascii); the API is less consistent, but for compression codecs it offers more control.


回答 3

import codecs
codecs.getencoder('hex_codec')(b'foo')[0]

在Python 3.3中工作(因此是“ hex_codec”而不是“ hex”)。

import codecs
codecs.getencoder('hex_codec')(b'foo')[0]

works in Python 3.3 (so “hex_codec” instead of “hex”).


回答 4

该方法binascii.hexlify()将转换bytesbytes代表ascii十六进制字符串的字符串。这意味着输入中的每个字节将转换为两个ascii字符。如果您想要一个真实的结果str,那么您可以.decode("ascii")的结果得到结果。

我提供了一个说明它的片段。

import binascii

with open("addressbook.bin", "rb") as f: # or any binary file like '/bin/ls'
    in_bytes = f.read()
    print(in_bytes) # b'\n\x16\n\x04'
    hex_bytes = binascii.hexlify(in_bytes) 
    print(hex_bytes) # b'0a160a04' which is twice as long as in_bytes
    hex_str = hex_bytes.decode("ascii")
    print(hex_str) # 0a160a04

从十六进制字符串"0a160a04"到可以回来了bytesbinascii.unhexlify("0a160a04")该还给b'\n\x16\n\x04'

The method binascii.hexlify() will convert bytes to a bytes representing the ascii hex string. That means that each byte in the input will get converted to two ascii characters. If you want a true str out then you can .decode("ascii") the result.

I included an snippet that illustrates it.

import binascii

with open("addressbook.bin", "rb") as f: # or any binary file like '/bin/ls'
    in_bytes = f.read()
    print(in_bytes) # b'\n\x16\n\x04'
    hex_bytes = binascii.hexlify(in_bytes) 
    print(hex_bytes) # b'0a160a04' which is twice as long as in_bytes
    hex_str = hex_bytes.decode("ascii")
    print(hex_str) # 0a160a04

from the hex string "0a160a04" to can come back to the bytes with binascii.unhexlify("0a160a04") which gives back b'\n\x16\n\x04'


回答 5

好的,如果您只关心Python 3,以下答案会稍微超出范围,但是即使您未指定Python版本,此问题也是Google的第一个热门产品,因此这是一种适用于Python 2 Python 3的方法。

我也在解释这个问题是关于将字节转换为 str类型:即在Python 2上为bytes-y,在Python 3上为Unicode-y。

鉴于此,我知道的最佳方法是:

import six

bytes_to_hex_str = lambda b: ' '.join('%02x' % i for i in six.iterbytes(b))

假设您尚未激活unicode_literalsPython 2 的未来,以下断言对于Python 2或Python 3都是正确的:

assert bytes_to_hex_str(b'jkl') == '6a 6b 6c'

(或者您可以''.join()用来省略字节之间的空格,等等。)

OK, the following answer is slightly beyond-scope if you only care about Python 3, but this question is the first Google hit even if you don’t specify the Python version, so here’s a way that works on both Python 2 and Python 3.

I’m also interpreting the question to be about converting bytes to the str type: that is, bytes-y on Python 2, and Unicode-y on Python 3.

Given that, the best approach I know is:

import six

bytes_to_hex_str = lambda b: ' '.join('%02x' % i for i in six.iterbytes(b))

The following assertion will be true for either Python 2 or Python 3, assuming you haven’t activated the unicode_literals future in Python 2:

assert bytes_to_hex_str(b'jkl') == '6a 6b 6c'

(Or you can use ''.join() to omit the space between the bytes, etc.)


回答 6

可以使用格式说明符%x02来格式化并输出一个十六进制值。例如:

>>> foo = b"tC\xfc}\x05i\x8d\x86\x05\xa5\xb4\xd3]Vd\x9cZ\x92~'6"
>>> res = ""
>>> for b in foo:
...     res += "%02x" % b
... 
>>> print(res)
7443fc7d05698d8605a5b4d35d56649c5a927e2736

it can been used the format specifier %x02 that format and output a hex value. For example:

>>> foo = b"tC\xfc}\x05i\x8d\x86\x05\xa5\xb4\xd3]Vd\x9cZ\x92~'6"
>>> res = ""
>>> for b in foo:
...     res += "%02x" % b
... 
>>> print(res)
7443fc7d05698d8605a5b4d35d56649c5a927e2736

回答 7

python 3.8中的新增功能,您可以将定界符参数传递给hex函数,如本例所示

>>> value = b'\xf0\xf1\xf2'
>>> value.hex('-')
'f0-f1-f2'
>>> value.hex('_', 2)
'f0_f1f2'
>>> b'UUDDLRLRAB'.hex(' ', -4)
'55554444 4c524c52 4142'

https://docs.python.org/3/library/stdtypes.html#bytes.hex

New in python 3.8, you can pass a delimiter argument to the hex function, as in this example

>>> value = b'\xf0\xf1\xf2'
>>> value.hex('-')
'f0-f1-f2'
>>> value.hex('_', 2)
'f0_f1f2'
>>> b'UUDDLRLRAB'.hex(' ', -4)
'55554444 4c524c52 4142'

https://docs.python.org/3/library/stdtypes.html#bytes.hex


回答 8

如果要将b’\ x61’转换为97或’0x61’,可以尝试以下操作:

[python3.5]
>>>from struct import *
>>>temp=unpack('B',b'\x61')[0] ## convert bytes to unsigned int
97
>>>hex(temp) ##convert int to string which is hexadecimal expression
'0x61'

参考:https : //docs.python.org/3.5/library/struct.html

If you want to convert b’\x61′ to 97 or ‘0x61’, you can try this:

[python3.5]
>>>from struct import *
>>>temp=unpack('B',b'\x61')[0] ## convert bytes to unsigned int
97
>>>hex(temp) ##convert int to string which is hexadecimal expression
'0x61'

Reference:https://docs.python.org/3.5/library/struct.html


如何在正则表达式中使用变量?

问题:如何在正则表达式中使用变量?

我想在a variable内部使用regex,该怎么办Python

TEXTO = sys.argv[1]

if re.search(r"\b(?=\w)TEXTO\b(?!\w)", subject, re.IGNORECASE):
    # Successful match
else:
    # Match attempt failed

I’d like to use a variable inside a regex, how can I do this in Python?

TEXTO = sys.argv[1]

if re.search(r"\b(?=\w)TEXTO\b(?!\w)", subject, re.IGNORECASE):
    # Successful match
else:
    # Match attempt failed

回答 0

从python 3.6开始,您还可以使用文字字符串插值(“ f-strings”)。在您的特定情况下,解决方案是:

if re.search(rf"\b(?=\w){TEXTO}\b(?!\w)", subject, re.IGNORECASE):
    ...do something

编辑:

既然评论中存在一些有关如何处理特殊字符的问题,我想扩展一下我的答案:

原始字符串(’r’):

在正则表达式中处理特殊字符时,您必须了解的主要概念之一是区分字符串文字和正则表达式本身。这是很好的解释在这里

简而言之:

假设您要匹配字符串\b之后,而不是查找单词边界。你必须写:TEXTO\boundary

TEXTO = "Var"
subject = r"Var\boundary"

if re.search(rf"\b(?=\w){TEXTO}\\boundary(?!\w)", subject, re.IGNORECASE):
    print("match")

这仅起作用,因为我们使用的是原始字符串(正则表达式以’r’开头),否则我们必须在正则表达式中写入“ \\\\ boundary”(四个反斜杠)。另外,如果没有’\ r’,\ b’将不再转换为单词边界,而是转换为退格键!

重新转义

基本上在任何特殊字符的前面放置一个空格。因此,如果您希望TEXTO中有特殊字符,则需要编写:

if re.search(rf"\b(?=\w){re.escape(TEXTO)}\b(?!\w)", subject, re.IGNORECASE):
    print("match")

注:对于任何版本> = 3.7蟒:!"%',/:;<=>@,和`都没有逃脱。仅对正则表达式中具有含义的特殊字符进行转义。_因为Python 3.3没有逃脱。(送。这里

大括号:

如果要在使用f字符串的正则表达式中使用量词,则必须使用双花括号。假设您要匹配TEXTO,然后再精确匹配2位数字:

if re.search(rf"\b(?=\w){re.escape(TEXTO)}\d{{2}}\b(?!\w)", subject, re.IGNORECASE):
    print("match")

From python 3.6 on you can also use Literal String Interpolation, “f-strings”. In your particular case the solution would be:

if re.search(rf"\b(?=\w){TEXTO}\b(?!\w)", subject, re.IGNORECASE):
    ...do something

EDIT:

Since there have been some questions in the comment on how to deal with special characters I’d like to extend my answer:

raw strings (‘r’):

One of the main concepts you have to understand when dealing with special characters in regular expressions is to distinguish between string literals and the regular expression itself. It is very well explained here:

In short:

Let’s say instead of finding a word boundary \b after TEXTO you want to match the string \boundary. The you have to write:

TEXTO = "Var"
subject = r"Var\boundary"

if re.search(rf"\b(?=\w){TEXTO}\\boundary(?!\w)", subject, re.IGNORECASE):
    print("match")

This only works because we are using a raw-string (the regex is preceded by ‘r’), otherwise we must write “\\\\boundary” in the regex (four backslashes). Additionally, without ‘\r’, \b’ would not converted to a word boundary anymore but to a backspace!

re.escape:

Basically puts a backspace in front of any special character. Hence, if you expect a special character in TEXTO, you need to write:

if re.search(rf"\b(?=\w){re.escape(TEXTO)}\b(?!\w)", subject, re.IGNORECASE):
    print("match")

NOTE: For any version >= python 3.7: !, ", %, ', ,, /, :, ;, <, =, >, @, and ` are not escaped. Only special characters with meaning in a regex are still escaped. _ is not escaped since Python 3.3.(s. here)

Curly braces:

If you want to use quantifiers within the regular expression using f-strings, you have to use double curly braces. Let’s say you want to match TEXTO followed by exactly 2 digits:

if re.search(rf"\b(?=\w){re.escape(TEXTO)}\d{{2}}\b(?!\w)", subject, re.IGNORECASE):
    print("match")

回答 1

您必须将正则表达式构建为字符串:

TEXTO = sys.argv[1]
my_regex = r"\b(?=\w)" + re.escape(TEXTO) + r"\b(?!\w)"

if re.search(my_regex, subject, re.IGNORECASE):
    etc.

请注意使用,re.escape这样如果您的文本中包含特殊字符,则不会这样解释它们。

You have to build the regex as a string:

TEXTO = sys.argv[1]
my_regex = r"\b(?=\w)" + re.escape(TEXTO) + r"\b(?!\w)"

if re.search(my_regex, subject, re.IGNORECASE):
    etc.

Note the use of re.escape so that if your text has special characters, they won’t be interpreted as such.


回答 2

if re.search(r"\b(?<=\w)%s\b(?!\w)" % TEXTO, subject, re.IGNORECASE):

这会将TEXTO中的内容作为字符串插入到正则表达式中。

if re.search(r"\b(?<=\w)%s\b(?!\w)" % TEXTO, subject, re.IGNORECASE):

This will insert what is in TEXTO into the regex as a string.


回答 3

rx = r'\b(?<=\w){0}\b(?!\w)'.format(TEXTO)
rx = r'\b(?<=\w){0}\b(?!\w)'.format(TEXTO)

回答 4

我发现通过将多个较小的模式串在一起来构建正则表达式模式非常方便。

import re

string = "begin:id1:tag:middl:id2:tag:id3:end"
re_str1 = r'(?<=(\S{5})):'
re_str2 = r'(id\d+):(?=tag:)'
re_pattern = re.compile(re_str1 + re_str2)
match = re_pattern.findall(string)
print(match)

输出:

[('begin', 'id1'), ('middl', 'id2')]

I find it very convenient to build a regular expression pattern by stringing together multiple smaller patterns.

import re

string = "begin:id1:tag:middl:id2:tag:id3:end"
re_str1 = r'(?<=(\S{5})):'
re_str2 = r'(id\d+):(?=tag:)'
re_pattern = re.compile(re_str1 + re_str2)
match = re_pattern.findall(string)
print(match)

Output:

[('begin', 'id1'), ('middl', 'id2')]

回答 5

我同意以上所有条件,除非:

sys.argv[1] 就像 Chicken\d{2}-\d{2}An\s*important\s*anchor

sys.argv[1] = "Chicken\d{2}-\d{2}An\s*important\s*anchor"

您不想使用re.escape,因为在这种情况下,您希望它的行为类似于正则表达式

TEXTO = sys.argv[1]

if re.search(r"\b(?<=\w)" + TEXTO + "\b(?!\w)", subject, re.IGNORECASE):
    # Successful match
else:
    # Match attempt failed

I agree with all the above unless:

sys.argv[1] was something like Chicken\d{2}-\d{2}An\s*important\s*anchor

sys.argv[1] = "Chicken\d{2}-\d{2}An\s*important\s*anchor"

you would not want to use re.escape, because in that case you would like it to behave like a regex

TEXTO = sys.argv[1]

if re.search(r"\b(?<=\w)" + TEXTO + "\b(?!\w)", subject, re.IGNORECASE):
    # Successful match
else:
    # Match attempt failed

回答 6

我需要搜索彼此相似的用户名,Ned Batchelder所说的话非常有用。但是,当我使用re.compile创建我的搜索项时,发现输出更清晰:

pattern = re.compile(r"("+username+".*):(.*?):(.*?):(.*?):(.*)"
matches = re.findall(pattern, lines)

可以使用以下命令打印输出:

print(matches[1]) # prints one whole matching line (in this case, the first line)
print(matches[1][3]) # prints the fourth character group (established with the parentheses in the regex statement) of the first line.

I needed to search for usernames that are similar to each other, and what Ned Batchelder said was incredibly helpful. However, I found I had cleaner output when I used re.compile to create my re search term:

pattern = re.compile(r"("+username+".*):(.*?):(.*?):(.*?):(.*)"
matches = re.findall(pattern, lines)

Output can be printed using the following:

print(matches[1]) # prints one whole matching line (in this case, the first line)
print(matches[1][3]) # prints the fourth character group (established with the parentheses in the regex statement) of the first line.

回答 7

您可以使用formatgrammer suger 尝试另一种用法:

re_genre = r'{}'.format(your_variable)
regex_pattern = re.compile(re_genre)  

you can try another usage using format grammer suger:

re_genre = r'{}'.format(your_variable)
regex_pattern = re.compile(re_genre)  

回答 8

您也可以为此使用format关键字。Format方法将{}占位符替换为您作为参数传递给format方法的变量。

if re.search(r"\b(?=\w)**{}**\b(?!\w)".**format(TEXTO)**, subject, re.IGNORECASE):
    # Successful match**strong text**
else:
    # Match attempt failed

You can use format keyword as well for this.Format method will replace {} placeholder to the variable which you passed to the format method as an argument.

if re.search(r"\b(?=\w)**{}**\b(?!\w)".**format(TEXTO)**, subject, re.IGNORECASE):
    # Successful match**strong text**
else:
    # Match attempt failed

回答 9

更多例子

我有带有流文件的configus.yml

"pattern":
  - _(\d{14})_
"datetime_string":
  - "%m%d%Y%H%M%f"

在我使用的python代码中

data_time_real_file=re.findall(r""+flows[flow]["pattern"][0]+"", latest_file)

more example

I have configus.yml with flows files

"pattern":
  - _(\d{14})_
"datetime_string":
  - "%m%d%Y%H%M%f"

in python code I use

data_time_real_file=re.findall(r""+flows[flow]["pattern"][0]+"", latest_file)

在Python中使用类型提示添加默认参数值

问题:在Python中使用类型提示添加默认参数值

如果我有这样的功能:

def foo(name, opts={}):
  pass

我想在参数中添加类型提示,该怎么办?我假设的方式给了我一个语法错误:

def foo(name: str, opts={}: dict) -> str:
  pass

以下内容不会引发语法错误,但似乎不是处理这种情况的直观方法:

def foo(name: str, opts: dict={}) -> str:
  pass

我在typing文档或Google搜索中找不到任何内容。

编辑:我不知道默认参数如何在Python中工作,但出于这个问题,我将保留上面的示例。通常,最好执行以下操作:

def foo(name: str, opts: dict=None) -> str:
  if not opts:
    opts={}
  pass

If I have a function like this:

def foo(name, opts={}):
  pass

And I want to add type hints to the parameters, how do I do it? The way I assumed gives me a syntax error:

def foo(name: str, opts={}: dict) -> str:
  pass

The following doesn’t throw a syntax error but it doesn’t seem like the intuitive way to handle this case:

def foo(name: str, opts: dict={}) -> str:
  pass

I can’t find anything in the typing documentation or on a Google search.

Edit: I didn’t know how default arguments worked in Python, but for the sake of this question, I will keep the examples above. In general it’s much better to do the following:

def foo(name: str, opts: dict=None) -> str:
  if not opts:
    opts={}
  pass

回答 0

您的第二种方法是正确的。

def foo(opts: dict = {}):
    pass

print(foo.__annotations__)

这个输出

{'opts': <class 'dict'>}

的确没有在PEP 484中列出它,但是类型提示是函数注释的一种应用,在PEP 3107中进行了记录。语法部分明确指出,关键字参数以这种方式与函数注释一起使用。

我强烈建议您不要使用可变的关键字参数。更多信息在这里

Your second way is correct.

def foo(opts: dict = {}):
    pass

print(foo.__annotations__)

this outputs

{'opts': <class 'dict'>}

It’s true that’s it’s not listed in PEP 484, but type hints are an application of function annotations, which are documented in PEP 3107. The syntax section makes it clear that keyword arguments works with function annotations in this way.

I strongly advise against using mutable keyword arguments. More information here.


回答 1

如果您使用的是类型输入(在Python 3.5中引入),则可以使用typing.Optional,其中Optional[X]等于Union[X, None]。它用于表示None允许使用的显式值。从键入。可选

def foo(arg: Optional[int] = None) -> None:
    ...

If you’re using typing (introduced in Python 3.5) you can use typing.Optional, where Optional[X] is equivalent to Union[X, None]. It is used to signal that the explicit value of None is allowed . From typing.Optional:

def foo(arg: Optional[int] = None) -> None:
    ...

回答 2

我最近看到了这种单线:

def foo(name: str, opts: dict=None) -> str:
    opts = {} if not opts else opts
    pass

I recently saw this one-liner:

def foo(name: str, opts: dict=None) -> str:
    opts = {} if not opts else opts
    pass

pip install-locale.Error:不支持的语言环境设置

问题:pip install-locale.Error:不支持的语言环境设置

完整的堆栈跟踪:

  ~ pip install virtualenv
Traceback (most recent call last):
  File "/usr/bin/pip", line 11, in <module>
    sys.exit(main())
  File "/usr/lib/python3.4/site-packages/pip/__init__.py", line 215, in main
    locale.setlocale(locale.LC_ALL, '')
  File "/usr/lib64/python3.4/locale.py", line 592, in setlocale
    return _setlocale(category, locale)
locale.Error: unsupported locale setting

在同一台服务器上,我成功运行pip install virtualenv了python2.7.x。

现在,我刚刚使用安装了python3.4 curl https://bootstrap.pypa.io/get-pip.py | python3.4

  ~ pip --version
pip 8.1.1 from /usr/lib/python3.4/site-packages (python 3.4)

pip uninstall virtualenv 也会引发相同的错误

Full stacktrace:

➜  ~ pip install virtualenv
Traceback (most recent call last):
  File "/usr/bin/pip", line 11, in <module>
    sys.exit(main())
  File "/usr/lib/python3.4/site-packages/pip/__init__.py", line 215, in main
    locale.setlocale(locale.LC_ALL, '')
  File "/usr/lib64/python3.4/locale.py", line 592, in setlocale
    return _setlocale(category, locale)
locale.Error: unsupported locale setting

On the same server, I successfully ran pip install virtualenv with python 2.7.x.

Now, I’ve just installed python3.4 using curl https://bootstrap.pypa.io/get-pip.py | python3.4.

➜  ~ pip --version
pip 8.1.1 from /usr/lib/python3.4/site-packages (python 3.4)

pip uninstall virtualenv throws the same error too


回答 0

根本原因是:您的环境变量LC_ALL丢失或以某种方式无效

简短答案-

只需运行以下命令:

$ export LC_ALL=C

如果在新的终端窗口中仍然出现错误,请在.bashrc文件底部添加错误。

长答案-

这是我的locale设置:

$ locale
LANG=en_US.UTF-8
LANGUAGE=
LC_CTYPE="C"
LC_NUMERIC="C"
LC_TIME="C"
LC_COLLATE="C"
LC_MONETARY="C"
LC_MESSAGES="C"
LC_PAPER="C"
LC_NAME="C"
LC_ADDRESS="C"
LC_TELEPHONE="C"
LC_MEASUREMENT="C"
LC_IDENTIFICATION="C"
LC_ALL=C

Python2.7

    $ uname -a
    Linux debian 3.16.0-4-amd64 #1 SMP Debian 3.16.7-ckt11-1+deb8u6 (2015-11-09) x86_64 GNU/Linux
    $ python --version
    Python 2.7.9
    $ pip --version
    pip 8.1.1 from /usr/local/lib/python2.7/dist-packages (python 2.7)
    $ unset LC_ALL
    $ pip install virtualenv
    Traceback (most recent call last):
      File "/usr/local/bin/pip", line 11, in <module>
        sys.exit(main())
      File "/usr/local/lib/python2.7/dist-packages/pip/__init__.py", line 215, in main
        locale.setlocale(locale.LC_ALL, '')
      File "/usr/lib/python2.7/locale.py", line 579, in setlocale
        return _setlocale(category, locale)
    locale.Error: unsupported locale setting
    $ export LC_ALL=C
    $ pip install virtualenv
    Requirement already satisfied (use --upgrade to upgrade): virtualenv in /usr/local/lib/python2.7/dist-packages

The root cause is: your environment variable LC_ALL is missing or invalid somehow

Short answer-

just run the following command:

$ export LC_ALL=C

If you keep getting the error in new terminal windows, add it at the bottom of your .bashrc file.

Long answer-

Here is my locale settings:

$ locale
LANG=en_US.UTF-8
LANGUAGE=
LC_CTYPE="C"
LC_NUMERIC="C"
LC_TIME="C"
LC_COLLATE="C"
LC_MONETARY="C"
LC_MESSAGES="C"
LC_PAPER="C"
LC_NAME="C"
LC_ADDRESS="C"
LC_TELEPHONE="C"
LC_MEASUREMENT="C"
LC_IDENTIFICATION="C"
LC_ALL=C

Python2.7

    $ uname -a
    Linux debian 3.16.0-4-amd64 #1 SMP Debian 3.16.7-ckt11-1+deb8u6 (2015-11-09) x86_64 GNU/Linux
    $ python --version
    Python 2.7.9
    $ pip --version
    pip 8.1.1 from /usr/local/lib/python2.7/dist-packages (python 2.7)
    $ unset LC_ALL
    $ pip install virtualenv
    Traceback (most recent call last):
      File "/usr/local/bin/pip", line 11, in <module>
        sys.exit(main())
      File "/usr/local/lib/python2.7/dist-packages/pip/__init__.py", line 215, in main
        locale.setlocale(locale.LC_ALL, '')
      File "/usr/lib/python2.7/locale.py", line 579, in setlocale
        return _setlocale(category, locale)
    locale.Error: unsupported locale setting
    $ export LC_ALL=C
    $ pip install virtualenv
    Requirement already satisfied (use --upgrade to upgrade): virtualenv in /usr/local/lib/python2.7/dist-packages

回答 1

运行以下命令(它将起作用):

export LC_ALL="en_US.UTF-8"
export LC_CTYPE="en_US.UTF-8"
sudo dpkg-reconfigure locales

Run the following command (it will work):

export LC_ALL="en_US.UTF-8"
export LC_CTYPE="en_US.UTF-8"
sudo dpkg-reconfigure locales

回答 2

有人可能会觉得有用。您可以将这些语言环境设置放在.bashrc文件中,该文件通常位于主目录中。
只需在.bashrc中添加此命令:
export LC_ALL=C
然后键入source .bashrc
Now,例如,当您通过ssh连接时,您无需每次都手动调用此命令。

Someone may find it useful. You could put those locale settings in .bashrc file, which usually located in the home directory.
Just add this command in .bashrc:
export LC_ALL=C
then type source .bashrc
Now you don’t need to call this command manually every time, when you connecting via ssh for example.


回答 3

尽管可以设置导出环境变量的语言环境,但每次启动会话时都必须这样做。以这种方式设置语言环境将永久解决问题:

sudo apt-get install locales
sudo locale-gen en_US.UTF-8
sudo echo "LANG=en_US.UTF-8" > /etc/default/locale

While you can set the locale exporting an env variable, you will have to do that every time you start a session. Setting a locale this way will solve the problem permanently:

sudo apt-get install locales
sudo locale-gen en_US.UTF-8
sudo echo "LANG=en_US.UTF-8" > /etc/default/locale

回答 4

[此答案仅适用于linux平台]

您应该知道的第一件事是,大多数语言环境配置文件的定位路径都可以从localedef --help以下位置获取:

$ localedef --help | tail -n 5
System's directory for character maps : /usr/share/i18n/charmaps
                       repertoire maps: /usr/share/i18n/repertoiremaps
                       locale path    : /usr/lib/locale:/usr/share/i18n
For bug reporting instructions, please see:
<https://bugs.launchpad.net/ubuntu/+source/glibc/+bugs>

看到最后一个/usr/share/i18n?这是您的xx_XX.UTF-8配置文件所在的位置:

$ ls /usr/share/i18n/locales/zh_*
/usr/share/i18n/locales/zh_CN  /usr/share/i18n/locales/zh_HK  /usr/share/i18n/locales/zh_SG  /usr/share/i18n/locales/zh_TW

怎么办 ?我们需要将它们编译为存档二进制文件。一种方式,例如假设我有/usr/share/i18n/locales/en_LOVE,我可以将其添加到编译列表(即/etc/locale-gen文件)中:

$ tail -1 /etc/locale.gen 
en_LOVE.UTF-8 UTF-8

并将其编译为二进制sudo locale-gen

$ sudo locale-gen 
Generating locales (this might take a while)...
  en_AG.UTF-8... done
  en_AU.UTF-8... done
  en_BW.UTF-8... done
  ...
  en_LOVE.UTF-8... done
Generation complete.

且以期望现在更新系统默认的语言环境LANGLC_ALL…等与此update-locale

sudo update-locale LANG=en_LOVE.UTF-8

update-locale实际上还意味着更新此/etc/default/locale文件,该文件将在登录时由系统提供以设置环境变量:

$ head /etc/default/locale 
#  File generated by update-locale
LANG=en_LOVE.UTF-8
LC_NUMERIC="en_US.UTF-8"
...

但是我们可能不想重启才能生效,因此我们可以将其来源到当前shell会话中的环境变量:

$ . /etc/default/locale

怎么sudo dpkg-reconfigure locales样 如果您玩转它,您将知道此命令基本上充当GUI来简化上述步骤,即Edit /etc/locale.gen-> sudo locale-gen->sudo update-locale LANG=en_LOVE.UTF-8

对于python,只要/etc/locale.gen包含该语言环境候选者并locale.gen进行编译,就setlocale(category, locale)可以正常运行locale.Error: unsupoorted locale setting。您可以通过观察文件来检查要在中设置的正确字符串en_US.UTF-8/ ,然后取消注释并根据需要对其进行编译。该文件中不带点的表示正确的字符串是和。en_US/....etcsetlocale()/etc/locale.genzh_CN GB2312zh_CNzh_CN.GB2312

[This answer is target on linux platform only]

The first thing you should know is most of the locale config file located path can be get from localedef --help :

$ localedef --help | tail -n 5
System's directory for character maps : /usr/share/i18n/charmaps
                       repertoire maps: /usr/share/i18n/repertoiremaps
                       locale path    : /usr/lib/locale:/usr/share/i18n
For bug reporting instructions, please see:
<https://bugs.launchpad.net/ubuntu/+source/glibc/+bugs>

See the last /usr/share/i18n ? This is where your xx_XX.UTF-8 config file located:

$ ls /usr/share/i18n/locales/zh_*
/usr/share/i18n/locales/zh_CN  /usr/share/i18n/locales/zh_HK  /usr/share/i18n/locales/zh_SG  /usr/share/i18n/locales/zh_TW

Now what ? We need to compile them into archive binary. One of the way, e.g. assume I have /usr/share/i18n/locales/en_LOVE, I can add it into compile list, i.e. /etc/locale-gen file:

$ tail -1 /etc/locale.gen 
en_LOVE.UTF-8 UTF-8

And compile it to binary with sudo locale-gen:

$ sudo locale-gen 
Generating locales (this might take a while)...
  en_AG.UTF-8... done
  en_AU.UTF-8... done
  en_BW.UTF-8... done
  ...
  en_LOVE.UTF-8... done
Generation complete.

And now update the system default locale with desired LANG, LC_ALL …etc with this update-locale:

sudo update-locale LANG=en_LOVE.UTF-8

update-locale actually also means to update this /etc/default/locale file which will source by system on login to setup environment variables:

$ head /etc/default/locale 
#  File generated by update-locale
LANG=en_LOVE.UTF-8
LC_NUMERIC="en_US.UTF-8"
...

But we may not want to reboot to take effect, so we can just source it to environment variable in current shell session:

$ . /etc/default/locale

How about sudo dpkg-reconfigure locales ? If you play around it you will know this command basically act as GUI to simplify the above steps, i.e. Edit /etc/locale.gen -> sudo locale-gen -> sudo update-locale LANG=en_LOVE.UTF-8

For python, as long as /etc/locale.gen contains that locale candidate and locale.gen get compiled, setlocale(category, locale) should work without throws locale.Error: unsupoorted locale setting. You can check the correct string en_US.UTF-8/en_US/....etc to be set in setlocale(), by observing /etc/locale.gen file, and then uncomment and compile it as desired. zh_CN GB2312 without dot in that file means the correct string is zh_CN and zh_CN.GB2312.


回答 5

对于Dockerfile,这对我有用:

RUN locale-gen en_US.UTF-8  
ENV LANG en_US.UTF-8  
ENV LANGUAGE en_US:en  
ENV LC_ALL en_US.UTF-8  

如何安装locale-gen?

docker ubuntu / bin / sh:1:locale-gen:找不到

For Dockerfile, this works for me:

RUN locale-gen en_US.UTF-8  
ENV LANG en_US.UTF-8  
ENV LANGUAGE en_US:en  
ENV LC_ALL en_US.UTF-8  

How to install locale-gen?

docker ubuntu /bin/sh: 1: locale-gen: not found


回答 6

我有同样的问题,对我没有用"export LC_ALL=c"

尝试export LC_ALL="en_US.UTF-8"(它将起作用)。

I had the same problem, and "export LC_ALL=c" didn’t work for me.

Try export LC_ALL="en_US.UTF-8" (it will work).


回答 7

该错误消息表示语言环境设置有问题。要解决此问题(如其他答案所示),您需要修改语言环境。

在Mac OS X Sierra上,我发现最好的方法是~/bash_profile按如下所示修改文件:

export LANG="en_US.UTF-8"
export LC_ALL="en_US.UTF-8"
export LC_CTYPE="en_US.UTF-8"

除非您使用以下命令重新加载bash配置文件,否则此更改在当前cli会话中不会立即显现source ~/.bash_profile

这个答案非常接近我发布给其他非相同,非重复的问题(即与pipenv不相关)的答案,但是碰巧需要相同的解决方案。

致主持人:尊敬;由于这个原因,我以前的答案被删除了,但是我觉得这有点愚蠢,因为实际上,无论何时只要错误是“语言环境问题”,这个答案都适用…但是可能会触发多种不同的情况,语言和环境该错误。

因此,A)将问题标记为重复项是没有意义的,而B)调整答案也没有意义,因为解决方法非常简单,在每种情况下都是相同的,并且无法从修饰中受益。

The error message indicates a problem with the locale setting. To fix this as indicated by other answers you need to modify your locale.

On Mac OS X Sierra I found that the best way to do this was to modify the ~/bash_profile file as follows:

export LANG="en_US.UTF-8"
export LC_ALL="en_US.UTF-8"
export LC_CTYPE="en_US.UTF-8"

This change will not be immediately evident in your current cli session unless you reload the bash profile by using: source ~/.bash_profile.

This answer is pretty close to answers that I’ve posted to other non-identical, non-duplicate questions (i.e. not related to pipenv) but which happen to require the same solution.

To the moderator: With respect; my previous answer got deleted for this reason but I feel that was a bit silly because really this answer applies almost whenever the error is “problem with locale”… but there are a number of differing situations, languages, and environments which could trigger that error.

Thus it A) doesn’t make sense to mark the questions as duplicates and B) doesn’t make sense to tailor the answer either because the fix is very simple, is the same in each case and does not benefit from ornamentation.


回答 8

Ubuntu:

$ sudo vi /etc/default/locale

在文件末尾添加以下设置。

LC_ALL = en_US.UTF-8

Ubuntu:

$ sudo vi /etc/default/locale

Add below setting at the end of file.

LC_ALL = en_US.UTF-8


访问列表的多个元素,知道它们的索引

问题:访问列表的多个元素,知道它们的索引

我需要从给定列表中选择一些元素,知道它们的索引。假设我要创建一个新列表,该列表包含给定列表[-2、1、5、3、8、5、6]中索引为1、2、5的元素。我所做的是:

a = [-2,1,5,3,8,5,6]
b = [1,2,5]
c = [ a[i] for i in b]

有什么更好的方法吗?像c = a [b]一样?

I need to choose some elements from the given list, knowing their index. Let say I would like to create a new list, which contains element with index 1, 2, 5, from given list [-2, 1, 5, 3, 8, 5, 6]. What I did is:

a = [-2,1,5,3,8,5,6]
b = [1,2,5]
c = [ a[i] for i in b]

Is there any better way to do it? something like c = a[b] ?


回答 0

您可以使用operator.itemgetter

from operator import itemgetter 
a = [-2, 1, 5, 3, 8, 5, 6]
b = [1, 2, 5]
print(itemgetter(*b)(a))
# Result:
(1, 5, 5)

或者您可以使用numpy

import numpy as np
a = np.array([-2, 1, 5, 3, 8, 5, 6])
b = [1, 2, 5]
print(list(a[b]))
# Result:
[1, 5, 5]

但实际上,您当前的解决方案很好。这可能是所有人中最整洁的。

You can use operator.itemgetter:

from operator import itemgetter 
a = [-2, 1, 5, 3, 8, 5, 6]
b = [1, 2, 5]
print(itemgetter(*b)(a))
# Result:
(1, 5, 5)

Or you can use numpy:

import numpy as np
a = np.array([-2, 1, 5, 3, 8, 5, 6])
b = [1, 2, 5]
print(list(a[b]))
# Result:
[1, 5, 5]

But really, your current solution is fine. It’s probably the neatest out of all of them.


回答 1

备择方案:

>>> map(a.__getitem__, b)
[1, 5, 5]

>>> import operator
>>> operator.itemgetter(*b)(a)
(1, 5, 5)

Alternatives:

>>> map(a.__getitem__, b)
[1, 5, 5]

>>> import operator
>>> operator.itemgetter(*b)(a)
(1, 5, 5)

回答 2

另一个解决方案可以通过pandas Series:

import pandas as pd

a = pd.Series([-2, 1, 5, 3, 8, 5, 6])
b = [1, 2, 5]
c = a[b]

然后,您可以根据需要将c转换回列表:

c = list(c)

Another solution could be via pandas Series:

import pandas as pd

a = pd.Series([-2, 1, 5, 3, 8, 5, 6])
b = [1, 2, 5]
c = a[b]

You can then convert c back to a list if you want:

c = list(c)

回答 3

比较五个提供的答案的执行时间的基础测试,但不是非常广泛的测试:

def numpyIndexValues(a, b):
    na = np.array(a)
    nb = np.array(b)
    out = list(na[nb])
    return out

def mapIndexValues(a, b):
    out = map(a.__getitem__, b)
    return list(out)

def getIndexValues(a, b):
    out = operator.itemgetter(*b)(a)
    return out

def pythonLoopOverlap(a, b):
    c = [ a[i] for i in b]
    return c

multipleListItemValues = lambda searchList, ind: [searchList[i] for i in ind]

使用以下输入:

a = range(0, 10000000)
b = range(500, 500000)

简单的python循环是使用lambda操作最快的一秒钟,紧随其后的是,mapIndexValues和getIndexValues始终与numpy方法相似,将列表转换为numpy数组后速度显着降低。最快的。

numpyIndexValues -> time:1.38940598 (when converted the lists to numpy arrays)
numpyIndexValues -> time:0.0193445 (using numpy array instead of python list as input, and conversion code removed)
mapIndexValues -> time:0.06477512099999999
getIndexValues -> time:0.06391049500000001
multipleListItemValues -> time:0.043773591
pythonLoopOverlap -> time:0.043021754999999995

Basic and not very extensive testing comparing the execution time of the five supplied answers:

def numpyIndexValues(a, b):
    na = np.array(a)
    nb = np.array(b)
    out = list(na[nb])
    return out

def mapIndexValues(a, b):
    out = map(a.__getitem__, b)
    return list(out)

def getIndexValues(a, b):
    out = operator.itemgetter(*b)(a)
    return out

def pythonLoopOverlap(a, b):
    c = [ a[i] for i in b]
    return c

multipleListItemValues = lambda searchList, ind: [searchList[i] for i in ind]

using the following input:

a = range(0, 10000000)
b = range(500, 500000)

simple python loop was the quickest with lambda operation a close second, mapIndexValues and getIndexValues were consistently pretty similar with numpy method significantly slower after converting lists to numpy arrays.If data is already in numpy arrays the numpyIndexValues method with the numpy.array conversion removed is quickest.

numpyIndexValues -> time:1.38940598 (when converted the lists to numpy arrays)
numpyIndexValues -> time:0.0193445 (using numpy array instead of python list as input, and conversion code removed)
mapIndexValues -> time:0.06477512099999999
getIndexValues -> time:0.06391049500000001
multipleListItemValues -> time:0.043773591
pythonLoopOverlap -> time:0.043021754999999995

回答 4

我确定已经考虑了这一点:如果b中的索引数量很小且恒定,则可以将结果写为:

c = [a[b[0]]] + [a[b[1]]] + [a[b[2]]]

如果索引本身是常数,甚至更简单…

c = [a[1]] + [a[2]] + [a[5]]

或者如果有连续范围的索引…

c = a[1:3] + [a[5]]

I’m sure this has already been considered: If the amount of indices in b is small and constant, one could just write the result like:

c = [a[b[0]]] + [a[b[1]]] + [a[b[2]]]

Or even simpler if the indices itself are constants…

c = [a[1]] + [a[2]] + [a[5]]

Or if there is a consecutive range of indices…

c = a[1:3] + [a[5]]

回答 5

这是一个更简单的方法:

a = [-2,1,5,3,8,5,6]
b = [1,2,5]
c = [e for i, e in enumerate(a) if i in b]

Here’s a simpler way:

a = [-2,1,5,3,8,5,6]
b = [1,2,5]
c = [e for i, e in enumerate(a) if i in b]

回答 6

我的答案不使用numpy或python集合。

查找元素的一种简单方法如下:

a = [-2, 1, 5, 3, 8, 5, 6]
b = [1, 2, 5]
c = [i for i in a if i in b]

缺点:此方法可能不适用于较大的列表。对于较大的列表,建议使用numpy。

My answer does not use numpy or python collections.

One trivial way to find elements would be as follows:

a = [-2, 1, 5, 3, 8, 5, 6]
b = [1, 2, 5]
c = [i for i in a if i in b]

Drawback: This method may not work for larger lists. Using numpy is recommended for larger lists.


回答 7

静态索引和小清单?

不要忘记,如果列表很小并且索引没有更改,例如在您的示例中,有时最好的方法是使用序列解压缩

_,a1,a2,_,_,a3,_ = a

性能要好得多,您还可以保存一行代码:

 %timeit _,a1,b1,_,_,c1,_ = a
10000000 loops, best of 3: 154 ns per loop 
%timeit itemgetter(*b)(a)
1000000 loops, best of 3: 753 ns per loop
 %timeit [ a[i] for i in b]
1000000 loops, best of 3: 777 ns per loop
 %timeit map(a.__getitem__, b)
1000000 loops, best of 3: 1.42 µs per loop

Static indexes and small list?

Don’t forget that if the list is small and the indexes don’t change, as in your example, sometimes the best thing is to use sequence unpacking:

_,a1,a2,_,_,a3,_ = a

The performance is much better and you can also save one line of code:

 %timeit _,a1,b1,_,_,c1,_ = a
10000000 loops, best of 3: 154 ns per loop 
%timeit itemgetter(*b)(a)
1000000 loops, best of 3: 753 ns per loop
 %timeit [ a[i] for i in b]
1000000 loops, best of 3: 777 ns per loop
 %timeit map(a.__getitem__, b)
1000000 loops, best of 3: 1.42 µs per loop

回答 8

一种pythonic方式:

c = [x for x in a if a.index(x) in b]

Kind of pythonic way:

c = [x for x in a if a.index(x) in b]

‘else if’的正确语法是什么?

问题:’else if’的正确语法是什么?

我是一名新的Python程序员,他正在从2.6.4跃升至3.1.1。在尝试使用“ else if”语句之前,一切都进行得很好。解释器在“ else if”中的“ if”之后给了我一个语法错误,原因是我似乎无法弄清。

def function(a):
    if a == '1':
        print ('1a')
    else if a == '2'
        print ('2a')
    else print ('3a')

function(input('input:'))

我可能缺少一些非常简单的东西;但是,我无法自行找到答案。

I’m a new Python programmer who is making the leap from 2.6.4 to 3.1.1. Everything has gone fine until I tried to use the ‘else if’ statement. The interpreter gives me a syntax error after the ‘if’ in ‘else if’ for a reason I can’t seem to figure out.

def function(a):
    if a == '1':
        print ('1a')
    else if a == '2'
        print ('2a')
    else print ('3a')

function(input('input:'))

I’m probably missing something very simple; however, I haven’t been able to find the answer on my own.


回答 0

在python中,“ else if”被拼写为“ elif”。
另外,您还需要在elif和之后加上一个冒号else

简单回答一个简单的问题。刚开始时(过去几周),我遇到了同样的问题。

因此,您的代码应为:

def function(a):
    if a == '1':
        print('1a')
    elif a == '2':
        print('2a')
    else:
        print('3a')

function(input('input:'))

In python “else if” is spelled “elif”.
Also, you need a colon after the elif and the else.

Simple answer to a simple question. I had the same problem, when I first started (in the last couple of weeks).

So your code should read:

def function(a):
    if a == '1':
        print('1a')
    elif a == '2':
        print('2a')
    else:
        print('3a')

function(input('input:'))

回答 1

你是说elif


回答 2

def function(a):
    if a == '1':
        print ('1a')
    elif a == '2':
        print ('2a')
    else:
        print ('3a')
def function(a):
    if a == '1':
        print ('1a')
    elif a == '2':
        print ('2a')
    else:
        print ('3a')

回答 3

自古以来,if/else ifPython中正确的语法是elif。顺便说一句,如果您有很多if/else.eg ,则可以使用字典。

d={"1":"1a","2":"2a"}
if not a in d: print("3a")
else: print (d[a])

对于msw,使用字典执行函数的示例。

def print_one(arg=None):
    print "one"

def print_two(num):
    print "two %s" % num

execfunctions = { 1 : (print_one, ['**arg'] ) , 2 : (print_two , ['**arg'] )}
try:
    execfunctions[1][0]()
except KeyError,e:
    print "Invalid option: ",e

try:
    execfunctions[2][0]("test")
except KeyError,e:
    print "Invalid option: ",e
else:
    sys.exit()

since olden times, the correct syntax for if/else if in Python is elif. By the way, you can use dictionary if you have alot of if/else.eg

d={"1":"1a","2":"2a"}
if not a in d: print("3a")
else: print (d[a])

For msw, example of executing functions using dictionary.

def print_one(arg=None):
    print "one"

def print_two(num):
    print "two %s" % num

execfunctions = { 1 : (print_one, ['**arg'] ) , 2 : (print_two , ['**arg'] )}
try:
    execfunctions[1][0]()
except KeyError,e:
    print "Invalid option: ",e

try:
    execfunctions[2][0]("test")
except KeyError,e:
    print "Invalid option: ",e
else:
    sys.exit()

回答 4

这是函数的一点重构(它不使用“ else”或“ elif”):

def function(a):
    if a not in (1, 2):
        a = 3
    print(str(a) + "a")

@ ghostdog74:Python 3要求在“打印”中加上括号。

Here is a little refactoring of your function (it does not use “else” or “elif”):

def function(a):
    if a not in (1, 2):
        a = 3
    print(str(a) + "a")

@ghostdog74: Python 3 requires parentheses for “print”.


回答 5

def function(a):
    if a == '1':
        print ('1a')
    else if a == '2'
        print ('2a')
    else print ('3a')

应该更正为:

def function(a):
    if a == '1':
        print('1a')
    elif a == '2':
        print('2a')
    else:
        print('3a')

正如您所看到的,else如果应该更改为elif,则’2’之后应该有冒号,否则,else语句之后应该有一个新行,并关闭print和括号之间的空间。

def function(a):
    if a == '1':
        print ('1a')
    else if a == '2'
        print ('2a')
    else print ('3a')

Should be corrected to:

def function(a):
    if a == '1':
        print('1a')
    elif a == '2':
        print('2a')
    else:
        print('3a')

As you can see, else if should be changed to elif, there should be colons after ‘2’ and else, there should be a new line after the else statement, and close the space between print and the parentheses.