【问题标题】:Python array printing in unicode and csv issueunicode和csv问题中的Python数组打印
【发布时间】:2015-06-02 12:45:02
【问题描述】:

dict1 是一个字典,对应的数组有 4 个样本元素,如下所示:

{u'OlpyplEJ_c_hFxyand_Wxw': [u'Inchin Bamboo Garden', u'Paradise Valley', 33.575816, -111.926234], 
u'_qvxFHGbnbrAPeWBVifJEQ': [u"Lenny's Sub Shop", u'Charlotte', 35.334993, -80.8129717], 
u's5yzZITWU_RcJzWOgjFecw': [u"Sergio's Italian Gardens", u'Las Vegas', 36.100414, -115.1265829]}

我正在使用 business_id 作为上述字典的键来打印数据

print "%s,%s" % (dict1[jd['business_id']], re.sub('\n|\r', '', jd['text']))

示例输出为:

[u"P&G's Pamela's Diner", u'Pittsburgh', 40.451723, -79.932833], The food here is over the top excessively greasy. So greasy that it made me sick to my stomach before I was done eating my meal. My husband and I split the chocolate chip pancakes and a ham and cheese omelette with potatoes and toast on the side. Not only was everything in a pool of grease, but it seemed to be margarine...not even real butter. I will never eat here again. I am gagging even thinking about this meal let aloe eating it again.

我有两个问题,第一个,如何从数组中的2个输出字符串中删除unicode标签u',我试过str()但是没用

第二个,当我导出为 .csv 文件时,“文本”中的逗号被拾取并将其拆分,我尝试在它周围使用“”,但我还是想不通

任何帮助将不胜感激

【问题讨论】:

    标签: python csv unicode unicode-string


    【解决方案1】:

    您可以通过将'unicode-escape' 传递给unicode.encode() 方法对unicode 进行编码来删除u。您可以使用列表理解:

    >>> l=[u"P&G's Pamela's Diner", u'Pittsburgh', 40.451723, -79.932833]
    >>> [i.encode('unicode-escape') if isinstance(i,unicode) else i for i in l]
    ["P&G's Pamela's Diner", 'Pittsburgh', 40.451723, -79.932833]
    

    关于您的第二个问题,因为默认情况下 python 将假定逗号作为分隔符。你可以为它定义一个服装分隔符。

    例如:

    import csv
    with open('file_name.csv', 'wb') as csvfile:
        spamwriter = csv.writer(csvfile, delimiter=' ')
        #do stuff
    

    【讨论】:

      【解决方案2】:

      “u”表示一个 unicode 字符串。您正在打印一个带有 unicode 字符串的 python 数组,所以这就是控制台上的内容。决定你想要的东西,例如', '.join(stuff)) 看起来不错。

      对于导出到 CSV,如果没有看到您的 CSV 代码,我无法帮助您,但我强烈建议您使用 Python 的 csv 模块来处理 CSV 输入和输出,并选择适合您数据的分隔符。

      【讨论】:

        猜你喜欢
        • 2023-03-22
        • 1970-01-01
        • 2013-09-04
        • 1970-01-01
        • 2021-06-16
        • 2016-10-08
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多