【问题标题】:How to encode list in python如何在python中编码列表
【发布时间】:2018-07-03 09:59:31
【问题描述】:

我使用美丽的汤从网站检索信息,我想将这些值存储在单个 csv 文件行中,因此我将这些信息存储在一个列表中,然后我将此列表存储在文件中。问题是我不处理特殊字符。

#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

执行代码后我得到:

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

这是 csv 文件中的结果

['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']

非常感谢您的帮助!

【问题讨论】:

  • 这是预期的输出,因为您正在编码为 utf8。你在这里有什么问题?以及如何写入 csv。您问题中的代码似乎缺少这一点。 minimal reproducible example
  • 对我来说很好......你能发布你用来写入 csv 的代码吗?

标签: python python-2.7


【解决方案1】:

如果你想要 csv 输出,你应该看看 csv 模块 - https://docs.python.org/3.6/library/csv.html?highlight=csv#csv.writer

这是一个示例(取自 Python 文档并针对您的示例进行了修改):

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

【讨论】:

    猜你喜欢
    • 2016-06-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-03-15
    • 2023-03-23
    • 2011-01-18
    • 2014-12-19
    相关资源
    最近更新 更多