python - 使用 python 创建一个中文文件夹

标签 python beautifulsoup

我现在遇到一个关于中文字符的问题。 我使用 beautifulsoup 来提取数据,并想创建一个使用提取数据名称的文件夹。 数据喜欢:

<A href="love">星座(1824)</A>

我想提取'星座(1824)',所以我喜欢

soup.find('a',href='love')

但是在控制台中,它出来了:

ÐÇ×ù(1824)

我在源代码的开头使用了“# -- coding:utf-8 --”。 这一定是一些编码问题,任何人都可以提供一些关于 python 使用非英语的好资料?

我想创建一个名为“星座(1824)”的文件夹 我愿意:

if not os.path.exists(dir_name):
        os.mkdir('./pic/'+dir_name) 

当我发现一个名为“Ç×ù(1824)”的文件夹存在时,为什么它仍然出现:

OSError: [Errno 17] File exists: './vguagua_pic/\xc3\x90\xc3\x87\xc3\x97\xc3\xb9(1824)'

谢谢

最佳答案

即使您的 .py 脚本是用 UTF-8 编写的,如果网页不是,解析的文本也可能不正确。

网页的编码实际上是GB-2312(或GB-18030),但BeautifulSoup将网页的编码错误地猜测为ISO-8859-1,并根据错误的假设,转换为UTF-8并导致mojibake。我们可以验证:

>>> b'\xc3\x90\xc3\x87\xc3\x97\xc3\xb9'.decode('utf8').encode('latin1').decode('gb2312')
'星座'

您可以将 from_encoding="gb2312"(在 bs4 中)或 fromEncoding="gb2312"(在 3.x 中)添加到 BeautifulSoup 构造函数以强制编码,如 Beautiful Soup Documentation 中所述(and also in Chinese 中文文档) .

关于python - 使用 python 创建一个中文文件夹,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11184048/

相关文章:

python2.7类型错误: not all arguments converted during string formatting

python - 检查类型 : How to check if something is a RDD or a DataFrame?

python - 为什么我不能正确使用 theano.tensor.argmax 和 theano.tensor.mean

html - 在 Python 中将 HTML 表转换为 Pandas 数据框

python - 如何从网站抓取 2 级网页

python - 在带有 BeautifulSoup 的 Python 3 中,print(soup.get_text()) 在以下代码 : 中生成错误 ('NoneType' object is not callable)

Python 副本 : How to inherit the default copying behaviour?

python - 来自 pogdesign.co.uk/cat/的数据抓取

python - 如何从该网页中抓取文本?

Python 使用带有函数的排序给出 TypeError : date_compare() missing 1 required positional argument: error