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()
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']
一个使用python
set
对象的简单脚本就可以做到这一点。这将检查不需要的单词集和输入文件行中的单词集是否都没有共同的单词在
^{pr2}$output.csv
中的输出是您可以看看csv模块文档https://docs.python.org/2/library/csv.html
这里是ipythin代码示例。在
请随意调整脚本以满足您的需要。在
请注意,我没有为可以这样处理的头提供特殊的处理。对于非常大的文件,这不是您应该如何处理的,因为整个文件都是读入ram的。在
^{pr2}$相关问题 更多 >
编程相关推荐