文件中存在unicode时,文件未在python中创建

2024-04-25 23:23:23 发布

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

我需要存储为文本文件的HTML文件。以网络标题的相同名称。我的代码出了问题,因此它无法在目录中创建文件。我有写目录的权限。我正在使用Ubuntu 12.04 LTS

目录/home/user1/ 文件名 打印名=Mathrubhumi Sports-ശ്രീനിക്ക്പച്ക്കൊട

文件名包含Unicode值

  import os
    from urllib import urlopen
    from bs4 import BeautifulSoup
    url= "http://www.mathrubhumi.com/sports/story.php?id=397111"
    raw = urlopen(url).read()
    soup = BeautifulSoup(raw,'lxml')
    texts = soup.findAll(text=True)
    name = soup.title.text
    name= name+'.txt'
    def contains_unicode(text):
        try:
            str(text)
        except:
            return True
        return False

    result = ''.join((text for text in texts if contains_unicode(text)))

    # Output to a file
    with open(os.path.join('/home/user1/textfiles',name,'w') as out:
        out.write(result)

请帮我调试一下


Tags: 文件textnamefromimport目录urlhome
1条回答
网友
1楼 · 发布于 2024-04-25 23:23:23

我尝试了这个方法,它成功了,它创建了一个名为Mathrub*.txt的文件,其中包含当前目录中的一些文本。你知道吗

import codecs
import os
from urllib import urlopen
from bs4 import BeautifulSoup
url= "http://www.mathrubhumi.com/sports/story.php?id=397111"
raw = urlopen(url).read()
soup = BeautifulSoup(raw,'lxml')
texts = soup.findAll(text=True)
name = soup.title.string
name= name+'.txt'
def contains_unicode(text):
    try:
        str(text)
    except:
        return True
    return False

result = ''.join((text for text in texts if contains_unicode(text)))
# Output to a file
with codecs.open(name,'w',encoding="utf-8") as out:
    out.write(result)

在添加编解码器部分之前,它大声抱怨试图编写一些它不知道如何解释的字符。你知道吗

相关问题 更多 >