2016-01-06 100 views
0
#define reader and process header 
csvReader = csv.reader(tmpfile) 
header = next(csvReader) 
template_name_index = header.index('TemplateName') 

我想让程序解析一个文件并查找标题'TemplateName',但我希望它能够找到标题,即使它的大写或小写。搜索不区分大小写的字符串

+4

可能重复的[如何将字符串转换为小写在Python?](http://stackoverflow.com/questions/6797984/how-to-convert-string-to-lowercase-in-python) – Erica

+0

我想要它能够找到这个值,不管它是大写,小写还是驼峰而不改变它。 –

+0

是的,但如果您将要搜索的字符串转换为小写字母,则可以搜索“templatename”。例如。 “RanDomTeMplAteNamE”.lower()变成“randomtemplatename” – Chris

回答

1

由于您正在查找字符串数组中的字符串,因此您可能必须遍历每个字符串。例如,这将字符串转换为小写在进行比较之前:

indexes = [index for index, name in enumerate(header) if name.lower() == "templatename"] 
if len(indexes) == 1: 
    index = indexes[0]    
    # There is at least one header matching "TemplateName" 
    # and index now points to the first header. 

注意,if声明认为有可能是没有头部或一个以上的标题匹配给定名称。为了您的安心,请注意lower()不会更改原始字符串的大小写。

您也可能会发现更明显的所有字符串转换在头调用索引,这看起来更像是原始的代码之前为小写:

try: 
    index = [name.lower() for name in header].index("templatename") 
except ValueError: 
    # There is no header matching "TemplateName" 
    # and you can use `pass` to just ignore the error. 
else: 
    # There is at least one header matching "TemplateName" 
    # and index now points to the first header. 

需要注意的是,像以前一样,lower()做不要更改实际标题的情况,因为它只在循环的上下文中完成。事实上,Python中的字符串是不可变的,所以你不能改变它们。

您可能还会考虑正则表达式。例如,这将搜索的情况下钝感无需转换字符串为小写:

import re 
indexes = [index for index, name in enumerate(header) if re.match(name, "TemplateName", re.I)] 

需要注意的是,如果你并不真正需要的指数,那么你就可以删除enumerate并简化环路一点。

+0

原谅我的无知,但我很新,并且我没有遵循.. –

+0

我编辑我的代码示例是更多详细,让我知道如果你还没有跟着。如果有什么具体的东西你不明白,请问。 – cr3

+0

非常感谢您的帮助。我现在要尝试几件事情,但我会让你知道。 –

相关问题