2013-03-11 85 views
0

我想从使用Beautifulsoup从URL解析的字符串中移除磅符号。磅符号出现以下错误。 SyntaxError:文件中的非ASCII字符'\ xa3'在函数中使用£并将其写入Python的csv中

我试图把这个# -*- coding: utf-8 -*-放在类的开头,但仍然出现错误。

这是代码。获得浮点数后,我想将其写入csv文件。

mainTag = SoupStrainer('table', {'class':'item'}) 
    soup = BeautifulSoup(resp,parseOnlyThese=mainTag) 
    tag= soup.findAll('td')[3] 
    price = tag.text.strip() 

    pr = float(price.lstrip(u'£').replace(',', '')) 
+1

您可以用字符串中的\ xa3替换£。 – Vortico 2013-03-11 04:00:57

回答

0

该问题可能是编码和字节与字符之一。 CSV文件使用什么编码?发生£符号的文件中有哪些字节序列?变量price中包含的字节是什么?您需要替换字符串中实际发生的字节。其中一个难题就是源代码中数据的内容。这就是源代码顶部的# -*- coding: utf-8 -*-标记显着的地方:它告诉python如何解释字符串文本中的字节。在替换字符之前,您可能需要(或想要)解码CSV文件中的字节以创建Unicode字符串。

我将指出documentation for the csv module in Python 2.7说:

Note: This version of the csv module doesn’t support Unicode input. Also, there are currently some issues regarding ASCII NUL characters. Accordingly, all input should be UTF-8 or printable ASCII to be safe; see the examples in section Examples.

的实施例部分包括以下代码演示通过csv模块以Unicode字符串提供的字节进行解码。

import csv 

def unicode_csv_reader(unicode_csv_data, dialect=csv.excel, **kwargs): 
    # csv.py doesn't do Unicode; encode temporarily as UTF-8: 
    csv_reader = csv.reader(utf_8_encoder(unicode_csv_data), 
         dialect=dialect, **kwargs) 
    for row in csv_reader: 
     # decode UTF-8 back to Unicode, cell by cell: 
     yield [unicode(cell, 'utf-8') for cell in row] 
相关问题