代码之家  ›  专栏  ›  技术社区  ›  Honest Escape

如何将中文字符和英文字符写入文件(Python 3)?

  •  0
  • Honest Escape  · 技术社区  · 7 年前

    我写了一个脚本来抓取YouTube播放列表页面的标题

    根据print语句,一切正常,直到我尝试将标题写入文本文件,这时我得到“UnicodeEncodeError:‘charmap’编解码器无法将字符编码到位…”

    我尝试在打开文件时添加“encoding='utf8',虽然这样可以修复错误,但所有的汉字都被随机的乱码字符所取代

    我还尝试用“replace”对输出字符串进行编码,然后对其进行解码,但这也只是用问号替换所有特殊字符

    这是我的代码:

    from bs4 import BeautifulSoup as BS
    import urllib.request
    import re
    
    playlist_url = input("gib nem: ")
    
    with urllib.request.urlopen(playlist_url) as response:
      playlist = response.read().decode('utf-8')
      soup = BS(playlist, "lxml")
    
    title_attrs = soup.find_all(attrs={"data-title":re.compile(r".*")})
    titles = [tag["data-title"] for tag in title_attrs]
    
    titles_str = '\n'.join(titles)#.encode('cp1252','replace').decode('cp1252')
    
    print(titles_str)
    with open("playListNames.txt", "a") as f:
        f.write(titles_str)
    

    下面是我用来测试的播放列表示例: https://www.youtube.com/playlist?list=PL3oW2tjiIxvSk0WKXaEiDY78KKbKghOOo

    2 回复  |  直到 7 年前
        1
  •  1
  •   Mark Tolonen    7 年前

    使用编码可以解决您的问题。Windows默认为ANSI编码,在美国Windows上为Windows-1252。它不支持中文。您应该使用 utf8 utf-8-sig 作为编码。一些Windows编辑器更喜欢后者,而采用ANSI。

    with open('playListNames.txt','w',encoding='utf-8-sig') as f:
    
        2
  •  0
  •   DuÅ¡an Maďar    7 年前

    这个 documentation 清楚文件编码:

    encoding 用于对 文件这只能在文本模式下使用。默认编码为 取决于平台(无论什么 locale.getpreferredencoding() 返回), 但是可以使用Python支持的任何文本编码。查看编解码器 支持的编码列表的模块。

    回答您上次评论中的问题。

    1. 您可以使用找到Windows上的首选编码

      import locale
      locale.getpreferredencoding()
      

    如果 playListNames.txt 创建时使用 open('playListNames.txt', 'w') 然后返回的值 场所getpreferredencoding() 用于编码。

    如果文件是手动创建的,则编码取决于编辑器的默认/首选编码。

    1. 提到 How to convert a file to utf-8 in Python? How do I convert an ANSI encoded file to UTF-8 with Notepad++? [closed] .