【问题标题】:How do i remove all character besides digits and "," from unicode string in python?如何从python中的unicode字符串中删除除数字和“,”之外的所有字符?
【发布时间】:2016-03-26 20:47:36
【问题描述】:

我正在使用 scrapy 编写小型爬虫。 XPath 之一是包含 price 后跟“zł”(波兰货币标记),问题是它被换行符、空格和非中断空格混淆了。 所以当我这样做的时候:

sel.xpath("div/div/span/span/text()[normalize-space(.)]").extract()

我明白了:

[u'\n            1\xa0740,00 z\u0142\n            \n            \n                ']

我想改成什么

[u'1740,00']

或简单地放入浮点变量。 什么是/最好/最简单/最快的方法?

【问题讨论】:

    标签: python xpath unicode scrapy


    【解决方案1】:

    您可以使用re.findall从字符串中提取字符:

    >>> import re
    >>> s = u'\n            1\xa0740,00 z\u0142\n            \n            \n            '
    >>> L = re.findall(r'[\d,]', s)
    >>> "".join(L)
    '1740,00'
    

    【讨论】:

    • 我做到了raw_price = sel.xpath("div/div/span/span/text()").extract() item['cena']= raw_price[0].strip()
    • @Lord_JABA: .strip() 只删除前导和尾随空格。也许,这里最灵活的解决方案是使用正则表达式。
    • 但是如果我们使用.strip(),这些字符不会出现在最终保存中
    • @Nikhil: s.strip() 会给你'1\xa0740,00 zł' 这不是 OP 想要的。
    • @eugeney 我在抓取时经常遇到这些字符,但是当我插入我的数据库时说mongo 为什么我得到实际数据或者即使我在 csv 上打印可能是我错了跨度>
    【解决方案2】:

    如果您只对 ascii 数字感兴趣,那么 the fastest method is to use bytes.translate():

    import string
    
    keep = string.digits.encode() + b',' # characters to keep
    delete = bytearray(set(range(0x100)) - set(bytearray(keep))) # to delete
    result = unicode_string.encode('ascii', 'ignore').translate(None, delete).decode()
    

    您可以使用 Unicode .translate() 更简洁地编写它:

    import string
    import sys
    
    keep = set(map(ord, string.digits + ',')) # characters to keep
    table = dict.fromkeys(i for i in range(sys.maxunicode + 1) if i not in keep)
    result = unicode_string.translate(table)
    

    结果是一样的,但是before Python 3.5, it is always dog-slow (the situation is better in Python 3.5 for ascii-only case)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-06-23
      • 2017-04-05
      • 2020-02-01
      • 2020-03-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-04-25
      相关资源
      最近更新 更多