简体   繁体   中英

How to print values for two columns of a .csv file using python

I am generating below data inside a for loop

2021-08-01 ['I', 'go', 'home']
2021-08-01 ['They', 'are', 'doing', 'great']
2021-08-02 ['We', 'are', 'here']
2021-08-02 ['You', 'are', 'awesome']

What I want to do is that I want to print above content to a.csv file of two columns Date & Text (Sample as below)

Date            Text
2021-08-01      ['I', 'go', 'home']
2021-08-01      ['They', 'are', 'doing', 'great']
2021-08-02      ['We', 'are', 'here']
2021-08-02      ['You', 'are', 'awesome']

    for key, val in res.items():
    keywords = []
    scores = []
    for index in val:
        keywords.append(index)
        scores.append(val[index])
    for i in find_clusters(keywords, scores):
        repA = list(dict.fromkeys(w for s in i for w in s.split()))
        print(key, repA)#this is where I print above values

To get file like

2021-08-01 ['I', 'go', 'home']
2021-08-01 ['They', 'are', 'doing', 'great']
2021-08-02 ['We', 'are', 'here']
2021-08-02 ['You', 'are', 'awesome']

you can even open file at start and use it with print()

fh = open("output.txt", "w")

# ... code ...

print(key, repA, file=fh)

# ... code ...

fh.close()

But this file will make problem to read it.

It would be better to use module csv to write it

import csv

fh = open("output.csv", "w")
writer = csv.writer(fh)

writer.writerow(["Date", "Text"])

# ... code ...

writer.writerow( [key, repA] )

# ... code ...

fh.close()

Or you can put all in list and use pandas to write csv or excel (or write to some database)

import pandas as pd


all_rows = []

# ... code ...

all_rows.append( [key, repA] )

# ... code ...

df = pd.DataFrame(all_rows, columns=["Date", "Text"])

df.to_csv("output.csv", index=False)

# or

df.to_excel("output.xlsx", index=False)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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