[英]Selectively delete rows in a csv file (Python)
我正在读取一个以空格分隔的数据的.csv
文件,其中包含一些不需要的单词。 我需要查找在给定行的任何列中是否存在不需要的单词,然后删除该行。
例如,如果unwanted_list = ['one', 'on']
,则对于具有列名称类标签test的输入.csv
文件;
输入:
ne two 1 five,
on one 2 we.
as we 20 on
cast as none vote
代表输出:
ne two 1 five,
cast as none vote
使用python set
对象的简单脚本应该可以解决问题。 这将检查不需要的单词集和输入文件行中的单词集都没有通用的单词;
def filter_unwanted_words():
unwanted_words = {'one', 'on'}
with open('input.csv', 'r') as f:
for line in f:
if set(line.split()).isdisjoint(unwanted_words):
yield line
def write_output():
with open('output.csv', 'w') as f:
f.writelines((line for line in filter_unwanted_words()))
if __name__ == '__main__':
write_output()
output.csv
的输出为;
ne two 1 five,
cast as none vote
您可以查看csv模块文档https://docs.python.org/2/library/csv.html
这是ipython中的示例代码。
In [1]: import csv
In [2]: f = open('plop.csv')
In [3]: exclude = set(('on', 'one'))
In [4]: reader = csv.reader(f, delimiter=' ')
In [5]: for row in reader:
...: if any(val in exclude for val in row):
...: continue
...: else:
...: print row
...:
['name', 'class', 'label', 'test']
['ne', 'two', '1', 'five,']
['cast', 'as', 'none', 'vote']
随时根据您的需求调整脚本。
请注意,我没有为标头提供特殊的处理,可以通过这种方式进行处理。 这不是应该处理非常大的文件的方式,因为整个文件都是读入ram的。
In [9]: f=open('plop.csv')
In [10]: reader = csv.reader(f.readlines()[1:], delimiter=' ') #skip headers
In [11]: for row in reader:
...: if any(val in exclude for val in row):
...: continue
...: else:
...: print row
...:
['ne', 'two', '1', 'five,']
['cast', 'as', 'none', 'vote']
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.