【问题标题】:How to remove rows from a csv file when compared to a list in a txt file using Python?与使用 Python 的 txt 文件中的列表相比,如何从 csv 文件中删除行?
【发布时间】:2015-01-09 18:50:26
【问题描述】:

我有一个包含 12.000 个字典条目的列表(只有单词,没有它们的定义)存储在一个 .txt 文件中。

我有一个完整的字典,其中包含 62.000 个条目(带有定义的单词)存储在 .csv 文件中。

我需要将.txt 文件中的小列表与.csv 文件中的较大列表进行比较,然后删除包含未出现在较小列表中的条目的行。换句话说,我想将这本字典清除为只有 12.000 个条目。

.txt 文件像这样在单独的行中逐行排序:

word1

word2

word3

.csv 文件的顺序如下:

ID(第 1 列)单词(第 2 列)含义(第 3 列)

如何使用 Python 完成此任务?

【问题讨论】:

  • 我会考虑使用像sqlite这样的数据库,并对数据使用executemany,然后将其写回csv?
  • 你不删除行,你打开输入文件,遍历每一行,测试它是否匹配所需的行,将你想要的行写入临时文件并将这个临时文件移动到完成后的原始文件。
  • @PauloScardine,OP 必须对与列表匹配的行进行索引搜索,我认为这非常低效
  • @Anzel,我正在搜索如何使用 executemany。
  • @PauloScardine,你有使用库 csv 的示例代码吗?

标签: python csv dictionary


【解决方案1】:

到目前为止,答案很好。如果你想要简约...

import csv

lookup = set(l.strip().lower() for l in open(path_to_file3))
map(csv.writer(open(path_to_file2, 'w')).writerow, 
    (row for row in csv.reader(open(path_to_file)) 
    if row[1].lower() in lookup))

【讨论】:

  • 我收到 SyntaxError: invalid syntax in line 11
  • 计算错误的括号...已修复。
【解决方案2】:

以下内容无法很好地扩展,但应该适用于指定的记录数。

import csv

csv_in = csv.reader(open(path_to_file, 'r'))
csv_out = csv.writer(open(path_to_file2, 'w'))
use_words = open(path_to_file3, 'r').readlines()

lookup = dict([(word, None) for word in use_words])

for line in csv_in:
    if lookup.has_key(line[0]):
        csv_out.writerow(line)

csv_out.close()

【讨论】:

  • lookup = set(l.rstrip() for l in open(path_to_file3)) 会占用较少的内存。并且套装可以很好地扩展。
  • 摆脱中间的 use_words 是一种性能改进,可以肯定的是,但可能会以显示正在发生的事情为代价。我想知道集合是否比哈希键搜索得更快,但是……听起来像是做实验的时候了。 :-)
  • 集合是没有值的字典。您节省了值对象的时间和内存占用,因此它们可以更好地扩展。
  • 啊...这完全有道理。谢谢!
  • 我刚刚复制并粘贴了你的代码,但它只是写了一个空文件。
【解决方案3】:

当前计算机中最不为人知的事实之一是,当您从文本文件中删除一行并保存文件时,编辑器大部分时间都会这样做:

  1. 将文件加载到内存中
  2. 用你想要的行写一个临时文件
  3. 关闭文件并将临时文件移到原始文件上

所以你必须加载你的单词表:

with open('wordlist.txt') as i:
    wordlist = set(word.strip() for word in i)  #  you said the file was small

然后你打开输入文件:

with open('input.csv') as i:
    with open('output.csv', 'w') as o:
        output = csv.writer(o)
        for line in csv.reader(i):  # iterate over the CSV line by line
            if line[1] not in wordlist:  # test the value at column 2, the word
                output.writerow(line) 

os.rename('input.csv', 'output.csv')

这是未经测试的,如果你发现任何错误,现在去做你的功课并在这里评论...... :-)

【讨论】:

    【解决方案4】:

    我会为此使用熊猫。数据集不大,可以在内存中完成。

    import pandas as pd
    
    words = pd.read_csv('words.txt')
    defs = pd.read_csv('defs.csv')
    words.set_index(0, inplace=True)
    defs.set_index('WORD', inplace=True)
    new_defs = words.join(defs)
    new_defs.to_csv('new_defs.csv')
    

    您可能需要操纵 new_defs 使其看起来像您想要的那样,但这就是它的要点。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-05-11
      • 2019-06-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多