【问题标题】:TypeError: coercing to unicode need string or buffer, list foundTypeError:强制转换为 unicode 需要字符串或缓冲区,找到列表
【发布时间】:2015-03-05 06:31:19
【问题描述】:

我正在编写一个代码,我需要将 txt 文件中的句子数据集转换为 csv 文件。这是我的代码,它工作正常,将输入 txt 文件转换为 csv 文件的格式。

但是,我无法制作输出 csv 文件。我是 python 编程的新手,所以我还不知道如何解决它。

这是我的代码:

def txtTOcsv():

output_csv = []

with open("dataset.txt", "r") as myfile:
    lines = myfile.readlines()
    for line in lines:
        row = line.split()
        for i in row[1:]:
            tokens  = (row[0],i)
            print tokens
            output_csv.append(tokens)

with open(output_csv,'w') as out_file:
    csv.writer(out_file)

它工作正常,直到

print tokens

并按照我的需要打印所有列之间带有逗号的列。但是当它转到将输出保存在 csv 文件中的行时。它给出了这个错误:

with open(output_csv,'w') as out_file:
TypeError: coercing to Unicode: need string or buffer, list found

任何帮助将不胜感激。谢谢。

【问题讨论】:

  • 这条output_csv.append(tokens) 行适合您吗?发布tokens 变量的值。
  • 是的,它确实有效。它输出这种格式的东西:` ('------', '-----------') ` @AvinashRaj

标签: python python-2.7 csv unicode


【解决方案1】:

output_csv 是一个列表,open() 需要一个文件名。

试试

with open("output.csv",'w') as out_file:
  csv.writer(out_file).writerows(output_csv)

【讨论】:

    【解决方案2】:

    除了 Tzach 发现的问题之外,还有一些其他问题:

    1. 没有理由将文件的所有行读入一个列表。

    2. 无需创建另一个列表来保存所有已处理的行。

    如果您处理的文件大小恰好为 5GB,那么您的代码会将该数据两次复制到内存中,这将需要 10GB 内存。这可能会占用您系统的内存。

    你可以做的是:

    1. 读入一行。
    2. 处理线路。
    3. 将处理后的行写入 csv 文件。
    4. 阅读下一行。

    这样,您一次只能将非常少量的文本读入内存。以下是处理任意大小文件的方法:

    import csv
    
    with open("data.txt", newline='') as infile:
        with open('csv3.csv', 'w', newline='') as outfile:
            writer = csv.writer(outfile)
    
            for line in infile:
                first_word, *words = line.split()
    
                for word in words:
                     writer.writerow([first_word, word])
    

    这行有点棘手:

    first_word, *words = line.split()
    

    如果你这样做:

    x, y = ["hello", "world"]
    

    python 会将“hello”分配给 x,将“world”分配给 y。也就是说,python取右边的第一个元素,赋值给左边的第一个变量,然后python取右边的第二个元素,赋值给左边的第二个变量,以此类推

    接下来,line.split() 返回一个列表,产生如下内容:

    first_word, *words = ["The", "apple", "is", "red"]
    

    再次,python 将右侧的第一个元素分配给左侧的第一个变量,因此“The”被分配给 first_word。接下来,* 告诉 python 收集右边的其余元素并将它们全部分配给变量 words,这使得 words 成为一个列表。

    【讨论】:

      猜你喜欢
      • 2014-03-02
      • 2021-03-28
      • 2015-02-01
      • 2014-12-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多