我应该如何修复代码以读取CSV文件中的所有行?

时间:2020-07-01 06:14:28

标签: python csv analysis

import csv
import ujson
from konlpy.tag import Okt

def ss(line):
    
    line = line.strip().replace(". ", ".\n")
    line = line.splitlines()
    return line 

def anal(analyzer, sent):
    tp =[]
    for i in sent:
        text = analyzer.pos(i)
        text_pos.append(text)
        
    return tp

input_file_name = r"data.csv"

with open(input_file_name, "r", encoding = "utf-8") as input_file:
    okt=Okt()
    
    for line in input_file:   
        sent = split_sentences(line)
        text_pos = get_pos(okt, sentence)

output_file_name=r"data1.json"
    
with open(output_file_name, "w", encoding="utf-8") as output_file:
    for get_pos in text_pos:
        text_str = ujson.dumps(text_pos, ensure_ascii=False)
        print(text_str, file=output_file)

这是我到目前为止的内容,但是仅CSV文件的最后一行正在读取和分析。我想修复代码以读取CSV文件的所有行(总共有5276行)并进行分析。我该怎么办?

1 个答案:

答案 0 :(得分:1)

在下面的循环中,您将覆盖循环的每次迭代中的句子和text_pos。

    for line in input_file:   
        sentence = split_sentences(line)
        text_pos = get_pos(okt, sentence)

在循环的最后一次迭代中,text_pos和句子将从最后一行开始。如果您是我,我会尝试在循环之前创建一个列表,并将get_pos的结果附加到列表中。稍后,您可以将每个结果写入输出文件。

免责声明:我没有使用Okt库的经验。希望我的预感是正确的。