【问题标题】:Python Data-Scraping Differentiation - millions vs. ones [closed]Python数据抓取差异 - 数百万与数[关闭]
【发布时间】:2018-02-11 02:19:46
【问题描述】:

我目前正在互联网上抓取一些表格,其中数字以不同的数字格式发布:

Animal - Left in Wild
Tigers - 18
Deer - 18m
Pigs - 180000

我已经设法从数字中去掉 m,但我想知道是否/如何使用 if 语句进行一些操作,以确保我准确地记录数字:

if animal.strip("m") == animal.strip("m"):
    left_in_wild = left_in_wild * 1000000

显然代码不起作用,但这是一个粗略的想法,我正在考虑如何解决这个问题。如果有人有任何他们认为有帮助的东西,请告诉我。

谢谢!

【问题讨论】:

    标签: python pandas csv web-scraping python-requests


    【解决方案1】:

    类似:

    import re
    
    def get_number(s):
        try: 
            i=int(re.match('(\d+)', s).group(1))
            if "m" in s:
                i*=1000000
            return i
        except:
            print "No Number"
    

    get_numbers("18m") 返回18000000

    如果您有数千个或其他内容,您甚至可以将其扩展为具有 elif "k" in s 块。

    【讨论】:

    • 如果要现场编译表达式,请改用re.match('(\d+)', s).group(1)。如果你想使用预编译的版本,把它放在你的函数之外,或者让它成为一个默认参数。
    • 好电话。更新。谢谢!
    【解决方案2】:

    一个简单的 IF 语句可以帮助您找到所需的内容:

    animal = "18m"
    
    if 'm' in animal:
        print animal.strip('m') + ",000,000"
    
    if 'k' in animal:
        print animal.strip('k') + ",000"
    

    返回:

    18,000,000
    

    【讨论】:

      猜你喜欢
      • 2020-10-12
      • 1970-01-01
      • 1970-01-01
      • 2012-03-15
      • 1970-01-01
      • 2014-05-24
      • 2021-12-12
      • 1970-01-01
      • 2018-11-29
      相关资源
      最近更新 更多