繁体   English   中英

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

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

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

2021-08-01 ['我','去','家']
2021-08-01 [“他们”、“正在”、“正在做”、“很棒”]
2021-08-02 [‘我们’、‘是’、‘这里’]
2021-08-02 ['你','是','很棒']

我想做的是我想将以上内容打印到两列DateText的 a.csv 文件中(示例如下)

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)

暂无
暂无

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

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