繁体   English   中英

Python writerows 只将NLTK FreqDist的最后一行写入csv文件

[英]Python writerows only writes the last row of NLTK FreqDist to a csv file

我一直在编写 Python 代码来使用 Python 列表 ( word_list ) 中包含的单词查找文本文档中包含的单词的频率分布该程序计算频率分布,我可以将它们打印到屏幕上,但是当我尝试编写频率分布到 .csv 文件它只会重复写入FreqDist的最后一行, FreqDist目录中有许多文本文件。 我的代码如下

CIK_List = []


for filename in glob.glob(os.path.join(test_path, '*.txt')):

 CIK = re.search(r"\_([0-9]+)\_", filename) # extract the CIK from the filename

 path = nltk.data.find(filename)
 raw = open(path, 'r').read()

 tokens = word_tokenize(raw)
 words = [h.lower() for h in tokens]
 f_dist = nltk.FreqDist([s.lower() for s in words])
 print(f_dist)

 wordcount = collections.Counter()

 CIK_List.append(CIK) 
 with open(file_path, 'w+', newline= '') as csv_file:
  writer = csv.writer(csv_file)
  writer.writerow(["CIK"] + word_list)
  for m in word_list:
    print([CIK.group(1)], [f_dist[m]], end='')

  for val in CIK_List:
     writer.writerows(([val.group(1)] + [f_dist[m] for m in word_list],))

问题是对于您读取的每个输入文件,您创建输出文件并写入

看看代码末尾的以下循环。 它有什么作用?

  for val in CIK_List:
     writer.writerows(([val.group(1)] + [f_dist[m] for m in word_list],))

CIK_List是正则表达式匹配的列表。 对于每个这样的正则表达式匹配,我们写出第一个匹配组(它是文件名的数字部分),然后我们写出一些不依赖于val东西 因此,当val遍历正则表达式匹配列表时,您会一次又一次地获得相同的输出。

您还多次打开文件,每个输入文件一次,每次打开文件时,您都会丢弃之前存在的内容。

您可能想要做的是打开输出文件一次,写出标题行,然后,对于每个输入文件,根据该输入文件的内容将一行写入输出文件:

CIK_List = []
with open(file_path, 'w+', newline= '') as csv_file:
    writer = csv.writer(csv_file)
    writer.writerow(["CIK"] + word_list)

    for filename in glob.glob(os.path.join(test_path, '*.txt')):

        CIK = re.search(r"\_([0-9]+)\_", filename) # extract the CIK from the filename

        path = nltk.data.find(filename)
        raw = open(path, 'r').read()
        
        tokens = word_tokenize(raw)
        words = [h.lower() for h in tokens]
        f_dist = nltk.FreqDist([s.lower() for s in words])
        print(f_dist)
        
        wordcount = collections.Counter()

        CIK_List.append(CIK) 
        for m in word_list:
            print([CIK.group(1)], [f_dist[m]], end='')

        writer.writerow([CIK.group(1)] + [f_dist[m] for m in word_list])

暂无
暂无

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

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