CSV下载未显示确切的值

时间:2016-06-02 16:15:37

标签: python csv

我的python代码的输出如下:

Anger 0.129971
Disgust 0.119636
Fear 0.216546
Joy 0.301672
Sadness 0.54521
Analytical 0.0
Confident 0.0
Tentative 0.0
Openness 0.817
Conscientiousness 0.571
Extraversion 0.157
Agreeableness 0.012
Emotional Range 0.401

其中text表示变量tone_name,decimal表示以下代码中的分数

我一直在运行以下代码以将输出转储到CSV文件中:

file = glob.glob(path)
# iterate over the list getting each file 
#writer = csv.writer(open('our-merged-data', mode='w')) 
for fle in file:
    # open the file and then call .read() to get the text 
    with open(fle) as f:

        data=tone_analyzer.tone(text='text')

    # iterate through tone analysis data
    tonename=[]; tonescore=[]
    for cat in data['document_tone']['tone_categories']:
     for tone in cat['tones']:
             tonename.append(tone['tone_name'])
             tonescore.append(tone['score'])
             print(tone['tone_name'],tone['score'])
    # output tone name and score to file
    output = fle.replace('.html', '')     
    X=output
    with open(X+'_tonename.csv', mode = 'w') as csvfile1:
        writer = csv.writer(csvfile1) 
        for i in tonename:
            writer.writerows((tone['tone_name'],tone['score']) for tone in cat['tones'])

不确定为什么但是当我打开输出CSV时我没有看到输出的所有值,而是我看到的所有内容如下:

Openness    0.817

Conscientiousness   0.571

Extraversion    0.157

Agreeableness   0.012

Emotional Range 0.401

Openness    0.817

Conscientiousness   0.571

Extraversion    0.157

Agreeableness   0.012

Emotional Range 0.401

Openness    0.817

Conscientiousness   0.571

Extraversion    0.157

Agreeableness   0.012

我不确定为什么我的输出没有完全附加到CSV上,我真的很感激您对此的帮助。

1 个答案:

答案 0 :(得分:0)

您已将cat分配给for循环中data['document_tone']['tone_categories']的每个元素。当您退出for循环时,cat将引用该列表中的 last 元素。这意味着cat是您想要的数据的子集。

接下来,在您编写csv文件的代码块中,您将重复tonename,这与您感兴趣的数据完全相同,但是您需要&#39 ;实际上并没有使用你想要的那个tonename列表的元素。出于这个原因,您需要在输出文件中重复元素,因为您正在获取cat的元素并将它们编写为与tonename中的元素数量相同的次数。这有点像写这个:

tonenames = ["a", "b", "c"]
cat = tonenames[-1]
for tname in tonenames:
    print(cat)

至少有点,我希望你能看到类比。

您感兴趣的是:

for fin in glob.glob(path):
    with open(fin) as f:
        # you're missing some code here - I've taken the next two lines from your previous stackoverflow posts by guessing
        text = f.read()
        data = tone_analyzer.tone(text)

    tonenames = []; tonescores = [];
    for cat in data['document_tone']['tone_categories']:
        for tone in cat['tones']:
            tonenames.append(tone['tone_name'])
            tonescores.append(tone['score'])
            print(tone['tone_name'],tone['score'])

    outfile = fin.replace('.html', '_tonename.csv')  
    with open(outfile, mode = 'w') as csvfile1:
        writer = csv.writer(csvfile1) 
        writer.writerows((name, score) for name, score in zip(tonenames, tonescores))

我可能会建议,考虑到您在StackOverflow上基本上在同一个编程问题上提出的其他问题的性质,您可以检查其中一些已回答的问题并对其他人提出的评论采取措施?他们中的一些人正在等待您的回答或更多的输入,而其他人可以通过查看答案旁边的勾号来关闭(如果您认为它已经解决了您的问题)。