小编San*_*mar的帖子

如何将"3.71B"和"4M"等字符串始终转换为Python中的数字?

我有一些相当严重的代码,几乎可以为雅虎财务公司制作有形的价格/账簿(一个很好的模块已经ystockquote获得了无形的价格/账面价值).

我的问题是:

对于计算中的一个变量,我发现的股票有10.89B和4.9M,其中B和M分别为亿和百万.我无法将它们转换为数字,这就是我所处的位置:

shares=''.join(node.findAll(text=True)).strip().replace('M','000000').replace('B','000000000').replace('.','') for node in soup2.findAll('td')[110:112]
Run Code Online (Sandbox Code Playgroud)

这是非常混乱的,但我认为如果不是,它会起作用

.replace('M','000000').replace('B','000000000').replace('.','') 
Run Code Online (Sandbox Code Playgroud)

我正在使用带变量的正则表达式.我想这个问题只是简单的正则表达式和变量.其他建议也很好.

编辑:

具体来说,我希望有一些适用于零,一或两位小数的数字,但这些答案看起来都很有帮助.

python regex finance yahoo-finance

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

如何根据文本节点的值添加xml节点

我正在玩一个 xml 文件@ http://www.jsphylosvg.com/examples/source.php?example=2&t=xml

如果 node 的值,我想插入一个节点name="Espresso"。

例如,我想从:

<clade>
<name>Espresso</name>
<branch_length>2.0</branch_length>
</clade>
Run Code Online (Sandbox Code Playgroud)

到:

<clade>
<name>Espresso</name>
<url>www.espresso.com</url>
<branch_length>2.0</branch_length>
</clade>
Run Code Online (Sandbox Code Playgroud)

根据我迄今为止所做的研究,我可以xpath用来查找包含 espresso 的节点(这应该有效,但它没有?)

import re, sys
import lxml.etree
f = open("test.xml", "r")
data = f.read()
tree = lxml.etree.XML(data)
if tree.xpath('//name/text()="Espresso"'):
    insert new child here
Run Code Online (Sandbox Code Playgroud)

此时应该可以使用uselxml.etree.Element来制作xml节点,并使用insert将它们附加到xml文档中

然而,虽然这在理论上听起来很棒,但我无法让它发挥作用。
我真的很感激任何帮助/建议

python xml xpath lxml

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

在Python中计算struct的CRC

我有以下结构,来自C中的NRPE守护进程代码:

typedef struct packet_struct {
  int16_t packet_version;
  int16_t packet_type;
  uint32_t crc32_value;
  int16_t result_code;
  char buffer[1024];
} packet;
Run Code Online (Sandbox Code Playgroud)

我想将这种数据格式从Python发送到C守护进程.CRC是在何时计算crc32_value的0,然后将其放入结构中.我的Python代码如下:

cmd = '_NRPE_CHECK'
pkt = struct.pack('hhIh1024s', 2, 1, 0, 0, cmd)
# pkt has length of 1034, as it should
checksum = zlib.crc32(pkt) & 0xFFFFFFFF
pkt = struct.pack('hhIh1024s', 2, 1, checksum, 0, cmd)
socket.send(....)
Run Code Online (Sandbox Code Playgroud)

守护程序正在接收以下值: version=2 type=1 crc=FE4BBC49 result=0

但它正在计算 crc=3731C3FD

计算CRC的实际C代码是:

https://github.com/KristianLyng/nrpe/blob/master/src/utils.c

它通过以下方式调用:

calculate_crc32((char *)packet, sizeof(packet));

当我将这两个函数移植到Python时,我会得到与zlib.crc32返回相同的函数.

我的struct.pack电话是否正确?为什么我的CRC计算与服务器的计算不同?

python struct crc pack nrpe

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

python将数字添加到字符串

尝试将count int添加到字符串的末尾(网站URL):

码:

  count = 0
  while count < 20:
    Url = "http://www.ihiphopmusic.com/music/page/" 
    Url = (Url) + (count)
    #Url = Url.append(count)
    print Url
Run Code Online (Sandbox Code Playgroud)

我想要:

http://www.ihiphopmusic.com/music/page/2
http://www.ihiphopmusic.com/music/page/3
http://www.ihiphopmusic.com/music/page/4
http://www.ihiphopmusic.com/music/page/5
Run Code Online (Sandbox Code Playgroud)

结果:

Traceback (most recent call last):
  File "grub.py", line 7, in <module>
    Url = Url + (count)
TypeError: cannot concatenate 'str' and 'int' objects
Run Code Online (Sandbox Code Playgroud)

python

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

如何避免在 Python 中覆盖信号处理程序?

我的实验代码是这样的:

import signal

def hi(signum, frame):
    print "hi"

signal.signal(signal.SIGINT, hi)
signal.signal(signal.SIGINT, signal.SIG_IGN)
Run Code Online (Sandbox Code Playgroud)

hi没有被打印,因为信号处理程序被signal.SIG_IGN.

我怎样才能避免这种情况?

python signals

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

使用wxPython显示wxBitmaps的问题

我一直在编写一个我一直在写的程序的问题,并希望得到一些帮助或输入.对于某些背景,我使用Python 2.7和wxPython来做一个流媒体网络摄像头客户端.客户端从自己的线程中获取服务器中的图像,并将它们放入队列中.然后,GUI线程从队列中获取这些图像并将它们转换为wxBitmap对象.这种情况每0.5秒发生一次,效果很好.我能够将wxBitmap对象保存为文件,因此我知道一切正常.

我遇到的问题实际上是让wxBitmap对象显示在我的GUI上.我似乎唯一可以做GUI的工作是显示一个灰色矩形,其中应该是网络摄像头图像.

onPaint()当我想要刷新屏幕时,这是我的调用:

    def onPaint(self,e):
            ## this is the function that actually draws and redraws the window
            ## to be displayed. I think it is something similar to blit()
            ## in other graphical display frameworks
            print "in onPaint"

            ## create the device context object (graphics painter)
            dc = wx.PaintDC(self)
            dc.BeginDrawing()

            ## draw the bitmap to the screen
            dc.DrawBitmap(self.imageBit,0,0,True)
            dc.EndDrawing()            

            ## test code.
            ## the following works and updates, which means that
            ## …
Run Code Online (Sandbox Code Playgroud)

python wxpython

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

如何使用readline支持重新安装ruby?

我已经按照https://github.com/wayneeseguin/rvm#installation上的说明通过RVM安装了Ruby 。

有关信息,我拥有所有档案(readline-5.2.tar.gz,readline-6.2.tar.gz,ruby-1.9.3-p327.tar.bz2,rubygems-1.8.24.tgz,wayneeseguin-rvm-stable。 tgz和yaml-0.1.4.tar.gz),但~/.rvm/archives我不想以任何方式重新下载它们。

当我做:

sudo /usr/bin/apt-get install build-essential openssl libreadline6 libreadline6-dev curl git-core zlib1g zlib1g-dev libssl-dev libyaml-dev libsqlite3-dev sqlite3 libxml2-dev libxslt-dev autoconf libc6-dev ncurses-dev automake libtool bison subversion pkg-config
Run Code Online (Sandbox Code Playgroud)

我得到:

Reading package lists... Done
Building dependency tree       
Reading state information... Done
Note, selecting 'libxslt1-dev' instead of 'libxslt-dev'
Note, selecting 'libncurses5-dev' instead of 'ncurses-dev'
libtool is already the newest version.
sqlite3 is already the newest version.
libxslt1-dev is already the newest version.
libc6-dev is …
Run Code Online (Sandbox Code Playgroud)

ruby rvm ubuntu-11.10

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

如何使用\ r在同一行上打印?

我做了一个下载器:

#!/usr/bin/env python
#-*- coding:utf-8 -*-

from __future__ import print_function, division, absolute_import, unicode_literals
import os
import argparse
try:
    from urllib2 import urlopen
except ImportError:
    from urllib.request import urlopen

# {{ Argument parser
parser = argparse.ArgumentParser(
    prog='downloader',
    description='a featureful downloader'
)

parser.add_argument(
    '-o',
    dest='outputfile'
)

parser.add_argument(
    '-r',
    dest='remotefile'
)

downloader = parser.parse_args()
# }}

# {{ default local filename
if downloader.outputfile:
    default_output_file = downloader.outputfile
else:
    default_output_file = os.path.split(downloader.remotefile)[-1]
# }}

u = urlopen(downloader.remotefile)
meta = u.info()
file_size  = int(dict(meta.items())['Content-Length'])
print("Downloading: %s …
Run Code Online (Sandbox Code Playgroud)

python stdout carriage-return python-3.x

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

如果存在其他参数,如何禁用参数?

在我的脚本中,argparse有一些参数会在另一个相反类型的参数传递时发生冲突.我想禁用--arg2if --arg1已存在.目前我还没有找到任何办法.

python argparse

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

python argparser用于部分选择的多个参数

我创建了一个像这样的argparser:

  parser = argparse.ArgumentParser(description='someDesc')
  parser.add_argument(-a,required=true,choices=[x,y,z])
  parser.add_argument( ... )
Run Code Online (Sandbox Code Playgroud)

但是,仅用于选择"x"而不用于选择"y,z",我想要一个额外的REQUIRED参数.例如.

python test -a x       // not fine...needs additional MANDATORY argument b
python test -a y       // fine...will run
python test -a z       // fine...will run  
python test -a x -b "ccc"       // fine...will run 
Run Code Online (Sandbox Code Playgroud)

如何使用ArgumentParser实现这一目标?我知道它可能与bash optparser

python argparse

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