将短语列表写入csv文件

2024-10-04 01:22:29 发布

您现在位置:Python中文网/ 问答频道 /正文

继前面的post之后,我编写了一些Python代码来计算大量文本文件中某些短语(包含在“word_list”变量中,列出了三个示例,但还有更多示例)的出现频率。我在下面编写的代码要求我获取列表中的每个元素,并将其插入字符串中,以便与每个文本文件进行比较。然而,当前代码只是将列表中最后一个短语的频率写入电子表格中的相关列,而不是全部写入。这只是一个缩进问题,没有将writerow放在正确的位置,还是代码中存在逻辑缺陷。还有什么方法可以避免使用列表到字符串赋值,以便将短语与文本文件中的短语进行比较

word_list = ['in the event of', 'frankly speaking', 'on the other hand']
S = {}
p = 0
k = 0

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

    for filename in glob.glob(os.path.join(path, '*.txt')):
     if filename.endswith('.txt'):
        f = open(filename)
        Fohone-K = filename[8:]
        data = f.read()
        # new code section from scratch file
        l = len(word_list)
        for s in range(l):
         phrase = word_list[s]
         S = data.count((phrase))
         if S:
          #k = k + 1
          print("'{}' match".format(Fohone-K), S)
         else:
          print("'{} no match".format(Fohone-K))
          print("\n")

          # for m in word_list:
     if S >= 0:
      print([Fohone-K] + [S])
     writer.writerow([Fohone-K] + [S])

当前的输出如下所示

enter image description here

当它需要看起来像这样的时候

enter image description here


Tags: csvpath代码in列表forfilenamelist
1条回答
网友
1楼 · 发布于 2024-10-04 01:22:29

你可能想做这样的事情:

import csv, glob, os

word_list = ['in the event of', 'frankly speaking', 'on the other hand']
file_path = 'out.csv'
path = '.'

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

    for filename in glob.glob(os.path.join(path, '*.txt')):
        if filename.endswith('.txt'):
            with open(filename) as f:
                postfix = filename[8:]
                content = f.read()
                matches = [content.count(phrase) for phrase in word_list]
                print(f"'{filename}' {'no ' if all(n == 0 for n in matches) else ''}match")
                writer.writerow([postfix] + matches)

关键问题是在每一行上写入S,这只包含一个计数。这里通过编写一组完整的匹配项来解决这个问题

相关问题 更多 >