[英]Split String with unicode and backslash with Python
我在从字符串中提取浮点数时遇到麻烦。 该字符串是webscraping的输出:
input = u'<strong class="ad-price txt-xlarge txt-emphasis " itemprop="price">\r\n\xa3450.00pw</strong>'
我想得到:
output: 3450.00
但我没有找到一种方法。 我尝试使用split / replace函数将其提取:
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']
因此,我仍然有与最终同样的问题\\
你有一个想法?
\\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'
问题是\\xa3
是unicode中的井号。 在执行split('\\xa')
时,您尝试将unicode字符split('\\xa')
。 您实际想要的输出是450.00
因为\\xa3450.00
转换为£450.00
。
str.split('\xa3')
应该可以在Python 3中工作。
注意: input
是关键字。 除非您明确打算重新分配它,否则建议不要将其用作变量。
还有另一种可能的解决方案:
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']
此代码可以帮助您:
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
从这里您可以轻松提取价值。
input.encode('utf-8').split('\xa3')[1].split('pw')[0]
>> 450.00
Voilà
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.