简体   繁体   中英

How to encode list in python

I retrieve information from the web site using beautiful soup and I want to store these values ​​in a single csv file row so i store this information in a list and later I store this list in the file. The problem is that I doesn't handle special characters.

#Répartition des prix moyen au m²
Repartition=[]          
Inferieur=soup.find_all("text", {"class" : "p6_segmentMainLabel-outer"})
Superieur=soup.find_all("text", {"class" : "p6_segmentValue-outer"})
for Data in list(zip(Inferieur,Superieur)):
    try:
        Inferieur,Superieur = Data
        Inferieur=Inferieur.string.encode('utf-8')
        Superieur=Superieur.string.encode('utf-8') 
        Data2=' = '.join([Inferieur,Superieur])
        print Data2
        Repartition.append(Data2)
    except NavigableString: 
            pass

After execution of the code I get :

Supérieur à 12.27 €/m² = 14 Inférieur à 12.27 €/m² = 14

here is the result in the csv file

['Sup\\xc3\\xa9rieur \\xc3\\xa0 12.27 \\xe2\\x82\\xac/m\\xc2\\xb2 = 14', 'Inf\\xc3\\xa9rieur \\xc3\\xa0 12.27 \\xe2\\x82\\xac/m\\xc2\\xb2 = 14']

Help is very much appreciated!

If you want csv output, you should have a look at the csv module - https://docs.python.org/3.6/library/csv.html?highlight=csv#csv.writer .

Here's an example (taken from the Python docs and modified for your example):

import csv
with open('output.csv', 'w', newline='') as csvfile:
    w = csv.writer(csvfile, quotechar='|', quoting=csv.QUOTE_MINIMAL)
    w.writerow(Repartition)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM