首页 > 解决方案 > 使用python在文件中搜索字符串

问题描述

我需要做很多'grep -i str file'回馈的事情,但多年来我一直在努力解决这个问题。

我有一个名为“siteLookup”的函数,我正在传递两个参数:str 's' 和 file_handle 'f'。我想a)确定字符串是否(在此示例中)出现(单个)site="XX001",并且b)如果找到,则取它所在的行,并返回我从中提取的另一个字段值[找到]线回呼叫者。(这是一个“csv”查找)。我定期进行此工作,但随后它将停止工作,我不明白为什么。

我已经尝试了所有不同的“开放”选项,包括 f.readlines 等。

#example line: 'XX001,-1,10.1.1.1/30,By+Location/CC/City Name/'
#example from lookupFile.csv: "XX001","Charleston","United States"

sf = open('lookupFile.csv')

def siteLookup(s, f):
    site = s.split(',')[0].strip().upper()
    if len(site) == 5:
        f.seek(0)
        for line in f:
            if line.find(site)>=0:
                city = line.split(',')[1].strip('"').upper()
                return city
            # else site not found 
            return -1
    else:  # len(site) != 5
        return -1

city = siteLookup(line, sf)
print(city)
sf.close()

我在这段代码中得到零匹配。(我已将此示例代码简化为单个搜索)。我期待取回与 5 位站点代码匹配的城市名称 - 站点代码是示例“行”中的第一个字段。

非常感谢任何帮助。

标签: python-2.7

解决方案


return的缩进错误——如果你要找的东西在第一行没有找到,它会返回 -1 并且不再看。

用于with open(...) as f:使您的代码更安全:

with open("lookupFile.csv","w") as f: f.write("""#example from lookupFile.csv: "XX001","Charleston","United States" """)

def siteLookup(s, f):
    site = s.split(',')[0].strip().upper()
    if len(site) == 5:
        f.seek(0)
        for line in f:
            if site in line:   # if site in line is easier for checking 
                city = line.split(',')[1].strip('"').upper()
                return city

        # wrongly indented - will return if site not in line
        # return -1

    # if too short or not found, return -1 - no need for 2 returns  
    return -1


line = 'XX001,-1,10.1.1.1/30,By+Location/CC/City Name/'

with open('lookupFile.csv') as sf:
    city = siteLookup(line, sf)
    print(city)

输出:

CHARLESTON

推荐阅读