如何在Python 2.7中创建一个小写集合小写

时间:2013-12-02 21:03:36

标签: python

我使用csv导入了5000个最常用单词的列表,我想确保它们都是小写的。我还需要把它变成一组。是否有一种特殊的方法可以做到这一点,因为它可以用来手动完成。但这段代码应该有效吗?

with open("most_common_words.csv", "rU") as csv_file: # Opens the file in a 'closure' so that when it's finished it's automatically closed"
    most_common = csv.reader(csv_file, delimiter = ',', quotechar = '"') # Create a csv reader instance

mcw_set = set(most_common.lower())

谢谢!

2 个答案:

答案 0 :(得分:5)

这将有效:

with open("most_common_words.csv", "rU") as csv_file:
    most_common = csv.reader(csv_file, delimiter = ',', quotechar = '"')
    mcw_set = set(x[0].lower() for x in most_common)

以下是generator expressions

的参考资料

答案 1 :(得分:0)

from itertools import imap
from operator import methodcaller

with open("most_common_words.csv", "rU") as csv_file: # Opens the file in a 'closure' so that when it's finished it's automatically closed"
    most_common = csv.reader(csv_file, delimiter = ',', quotechar = '"') # Create a csv reader instance

mcw_set = set(imap(methodcaller('lower'), most_common))