【问题标题】:Writing out a list of phrases to a csv file将短语列表写入 csv 文件
【发布时间】:2020-12-20 13:11:47
【问题描述】:

从早期的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

【问题讨论】:

  • 这可能是您练习调试技能的好时机。以下两个参考资料为调试代码提供了极好的建议。 Six Debugging Techniques for Python ProgrammersUltimate Guide to Python Debugging
  • 我怎样才能把输出写成一行而不是一列?
  • 您能否提供输入文件的示例,您能否在输出中显示您当前得到的内容,以及您想要得到的内容?
  • 输入只是目录中的一系列文本文件,每个文件都包含大量文本。输出应该是一个 .csv 文件,第一列中包含文件名,以及后续行中的短语数。我得到的是在第一列中重复的文本文件名(取决于列表中的短语数)和第二列中每个文件的短语数。我在原始问题中添加了上面实际和所需输出的屏幕截图。
  • 请在发布代码之前修复您的语法错误和缩进 - 您发布的代码不会运行,即使有人输入了文件。

标签: python python-3.x string nlp export-to-csv


【解决方案1】:

你可能想要这样的事情:

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,它只包含一个计数。通过编写一整套匹配项可以解决此问题。

【讨论】:

  • 刚刚在一小部分短语和文本文件上尝试了您的代码,它运行良好。明天将在更大的样本上运行它,但感谢您的帮助。
猜你喜欢
  • 2016-09-26
  • 1970-01-01
  • 2012-12-11
  • 1970-01-01
  • 1970-01-01
  • 2014-06-30
相关资源
最近更新 更多