简体   繁体   English

打印到CSV会在每个字符之间引起空格?

[英]Printing to CSV causes a space between every character?

I am trying to print to CSV with Python3.6. 我正在尝试使用Python3.6打印到CSV。 When I print in console, it looks fine, but when I try to print to CSV, it prints like | | this 当我在控制台中打印时,它看起来不错,但是当我尝试打印为CSV时,它的打印结果like | | this like | | this like | | this . like | | this

ie with spaces between each char, and | 即每个字符之间有空格,和| between each space. 每个空间之间。

I am calling the translate function here. 我在这里称翻译功能

Sample response : 样品回复:

{
  "translations": [{
    "translation": "Hola"
  }],
  "word_count": 1,
  "character_count": 5
}

Here are the relevant extracts : 以下是相关摘录:

with open('C:\\Users\\SimonTheKing\\Desktop\\file.csv', 'w') as csvfile:
    spamwriter = csv.writer(csvfile, delimiter=' ',
                            quotechar='|', quoting=csv.QUOTE_MINIMAL)


    # Print the contents
    for x in range(len(first_column)): #iterates over every row in an xlsx
        translation = language_translator.translate(
            model_id='123',
            text=first_column[x].value #reads from openpyxl xlsx
        )
        print(translation) #prints as expected
        spamwriter.writerow(translation) #prints a space between every char

Can anyone offer some guidance please ? 任何人都可以提供一些指导吗?

Writerow takes an iterable as an argument, so when you give it single row string, it treats the string as an iterable and writes it with the standard space(delimiter set earlier) between each element. Writerow以一个Iterable作为参数,因此当您给它单行字符串时,它将字符串视为一个Iterable,并使用每个元素之间的标准空格(较早设置的定界符)进行写入。

You will need to either set the row to a list with [translation] or give it a list. 您将需要使用[translation]将行设置为列表,或为其提供列表。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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