【问题标题】:Split String with unicode and backslash with Python使用 unicode 分割字符串并使用 Python 使用反斜杠
【发布时间】:2016-06-23 09:49:13
【问题描述】:

我在从字符串中提取浮点数时遇到问题。该字符串是网页抓取的输出:

input = u'<strong class="ad-price txt-xlarge txt-emphasis " itemprop="price">\r\n\xa3450.00pw</strong>'

我想得到:

output: 3450.00

但我没有找到办法。我尝试使用拆分/替换功能将其提取出来:

word.split("\xa")
word.replace('<strong class="ad-price txt-xlarge txt-emphasis " itemprop="price">\r\n\xa','')

我尝试使用re 库。它也不好用,它只提取450.00

import re
num = re.compile(r'\d+.\d+')
num.findall(word)
[u'450.00']

因此,\ 最后我仍然有同样的问题 你有想法吗 ?

【问题讨论】:

  • 你尝试了什么?
  • 什么意思?我尝试使用的功能?
  • 是的.. 我们希望查看您的代码,以便我们可以帮助您找出哪里出错

标签: python unicode split web-scraping


【解决方案1】:

\xa3 是井号。

import unidecode 
print unidecode.unidecode(input)

<strong class="ad-price txt-xlarge txt-emphasis " itemprop="price">
PS450.00pw</strong>

要从中获取数字,您最好使用正则表达式:

import re
num = re.compile(r'\d+.\d+')
num.findall(input)[0]

结果

'450.00'

【讨论】:

  • 几乎!事实上你没有得到正确的结果,你没有提取 3450.00 而只是 450.00
  • 真正的答案是 450.00 英镑。那你为什么要 345.00 呢?
【解决方案2】:

对此还有另一种可能的解决方案:

import re

x = u'<strong class="ad-price txt-xlarge txt-emphasis " itemprop="price">\r\n\xa3450.00pw</strong>'
print re.findall(r'\d+.\d*', x)

输出:[u'450.00']

【讨论】:

  • 这是@Rahul K P 答案的副本。
【解决方案3】:

问题是\xa3 是 unicode 中的井号。当您执行 split('\xa') 时,您正试图将 unicode 字符分成两半。您真正想要的输出是450.00,因为\xa3450.00 转换为£450.00

str.split('\xa3')

应该在 Python 3 中工作。


注意: input 是一个关键字。除非您明确表示要重新分配它,否则我建议不要将其用作变量。

【讨论】:

  • 这不起作用,因为它是一个非 ascii 字符:UnicodeDecodeError: 'ascii' codec can't decode byte 0xa3 in position 0: ordinal not in range(128)
  • @th3an0maly 这是因为您的控制台不支持 Unicode 字符。那完全是一个不同的问题。它应该在 IDLE 中工作。
  • 巧合的是,我正在使用 IDLE :)
  • 好吧..我不能发布截图,但它对我有用。
  • 我已经删除了我的反对票,因为我不确定发生了什么:)
【解决方案4】:
input.encode('utf-8').split('\xa3')[1].split('pw')[0]

>> 450.00

【讨论】:

  • 但你甚至不知道pw 应该是什么。这可能不是一个不变的。
  • 很好的尝试,但它没有。我要提取 3450.00
  • @Jb_Eyd \xa3450.00 字面意思是 PS450.00
  • @th3an0maly 非常感谢!!!我没有意识到它是 unicode 的一部分!
  • 无需编码,只需在u'\xa3' 上拆分,但实际上OP 的原始re 解决方案已经给出了正确答案,但没有意识到。
【解决方案5】:

此代码可能会对您有所帮助:

import requests 
from bs4 import BeautifulSoup

input = u'<strong class="ad-price txt-xlarge txt-emphasis " itemprop="price">\r\n\xa3450.00pw</strong>'
soup = BeautifulSoup(input)
# Find all script tags
for n in soup.find_all('strong'):
    # Check if the src attribute exists
    if 'src' in n.attrs:
        value = n['src']
        print value

我承认我没有运行它,但输出应该是:

\r\n\xa3450.00pw

您可以从这里轻松提取价值。

【讨论】:

  • 感谢您的回答。不,它确实有效,因为您仍然有同样的问题。 IE。用 \xa 周围提取
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-02-22
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多