如何使用 python 打印 .csv 文件两列的值

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

我在 for 循环中生成以下数据

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']

我想做的是将上面的内容打印到两列的.csv文件中Date & Text(示例如下)

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

获取类似

的文件
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']

您甚至可以在开始时打开文件并使用 print()

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

# ... code ...

print(key, repA, file=fh)

# ... code ...

fh.close()

但是这个文件会导致阅读困难。

最好用模块csv来写

import csv

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

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

# ... code ...

writer.writerow( [key, repA] )

# ... code ...

fh.close()

或者你可以把所有的都放在列表中,然后用pandas写成csvexcel(或者写到某个数据库)

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)