Skip to main content
 首页 » 编程设计

附加到列表的 Python 将删除 unicode

2024年10月01日6bjzhanghao

我有字符串:a więc

当我打印它时一切正常,但是当我追加到列表时它会更改为 u'a wi\u0119c'。 然后我试图保存到文件(使用 json.dumps 因为列表中有很多单词)并且它保持 u'a wi\u0119c'。

如何修复使 u'a wi\u0119c' 变为 więc?

import urllib2 
from bs4 import BeautifulSoup 
import sys 
import json 
reload(sys) 
sys.setdefaultencoding('utf-8') 
 
def scrapsl(): 
    wordlist = [] 
    deflist = [] 
    soup = BeautifulSoup(urllib2.urlopen('https://sjp.pl/slownik/lp.phtml?page=1').read(), "html.parser") 
    nextpage = soup.find_all('b')[1].a.get('href') 
    for i in range(2, 52): 
        wordlist.append(unicode(soup.find_all('tr')[i].td.text)) 
        print(unicode(soup.find_all('tr')[i].td.text)) 
        sp = BeautifulSoup(urllib2.urlopen('https://sjp.pl/' + str(wordlist[(len(wordlist) - 1)]).replace(' ', "+")).read(), "html.parser") 
        deflist.append({wordlist[(len(wordlist) - 1)]: sp.find_all('p')[3].text}) 
        print(str(i) + "\\52") 
    print wordlist 
    writelist = [] 
    writelist.append(wordlist) 
    writelist.append(deflist) 
    ftw = open("slownik.txt", 'w') 
    ftw.write(json.dumps(writelist)) 
    ftw.close() 
scrapsl() 

谢谢

请您参考如下方法:

这很好,您无法修复它,因为这是 Python 2.x 中的设计。打印列表时,每个值首先由 repr 函数处理,因此您打印的是 repr 值的列表,这可能与您看到的不同在 print 之后,因为 print(value) 输出 str(value),而不是 repr(value).

如果您绝对需要查看实际值(即 str(value),而不是 repr(value)),只需升级到 Python 3.x。