使用英镑符号在Python中的函数,并将其写入csv

2024-04-25 07:02:12 发布

您现在位置:Python中文网/ 问答频道 /正文

我想从使用Beautifulsoup从url解析的字符串中删除井号。我得到了如下的磅符号错误。 SyntaxError:文件中的非ASCII字符“\xa3”

我试图把这个# -*- 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(',', ''))

Tags: 文件字符串urltag错误ascii符号字符
1条回答
网友
1楼 · 发布于 2024-04-25 07:02:12

问题很可能是编码问题,以及字节与字符的关系。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]

相关问题 更多 >