Python:根据查找在行中查找字符串

时间:2012-10-01 15:35:46

标签: python dynamic if-statement find

是否可以在字符串中查找值,其中值是CSV中任何字段值之一。 E.G ...

values.csv:

field1,field2,field3
1,abc,123
2,def,456
3,ghi,789
4,jkl,012,
..,..,..

因此,使用CSV中的字段(不会非常大),我可以找到该行(已定义)是否包含任何这些值(即'abc | def | ghi | jkl'),因此预计会有以下结果:

'This string is abc' = TRUE
'This is a string' = FALSE
'This def is good' = TRUE

所以在这里我只想找一个使用动态值的if语句,所以我可以将它放到我的代码中...我目前打印出line就像打样阶段一样,所以我已经有了此

更新:

@ korylprince的答案在这里有所帮助,将功能稍微改为以下内容:

def checkString(text):
    for search in searches:
        #print search <--- TESTING
        if search not in text:
            #print "FALSE" <--- TESTING
            test="FALSE"
        else:
            #print "TRUE" <--- TESTING
            test="TRUE"
            break
     #print test <--- TESTING
     ....

干杯,

3 个答案:

答案 0 :(得分:3)

# Your parsed csv file
csv = ['abc', '123', '2', 'def', '456', '3', 'ghi', '789', '4', 'jkl', '012']
lines = ['This string is abc', 'This is a string', 'This def is good']

for line in lines:
    print line, ':', any(word in line for word in csv)

输出:

This string is abc : True
This is a string : False
This def is good : True

答案 1 :(得分:1)

有点难以理解你想要的东西。

根据你的说法,我认为你的意思是你有一个csv文件,values.csv。

从这个csv文件中你想要获取第二列中的所有值并将它们放在一个列表中。

然后,对于您提供的任何字符串,您希望查看其中一个值是否在字符串中。

试试这个:

# open file and parse values
with open('values.csv') as f:                                               
    searches = [x.split(',')[1] for x in f.read().splitlines()]

# function to check string
def checkString(text):
    # iterate over searches and check each one
    for search in searches:
        if search in text:
            return True
    return False

有更有效的方法可以做到这一点,但如果你只有一些记录和字符串(几百甚至几千),这应该没问题。

答案 2 :(得分:1)

这次使用DictReader模块中的csv进行了另一种变体:

import csv

lines = ['This string is abc', 'This is a string', 'This def is good']

with open(r'C:\Users\BioGeek\Desktop\values.csv') as f:
    reader = csv.DictReader(f)
    for row in reader:
        word = row[reader.fieldnames[1]] # only take words from the second column
        for line in lines:
            print "Is '{0}' in '{1}': {2}".format(word, line, word in line)

产生输出:

Is 'abc' in 'This string is abc': True
Is 'abc' in 'This is a string': False
Is 'abc' in 'This def is good': False
Is 'def' in 'This string is abc': False
Is 'def' in 'This is a string': False
Is 'def' in 'This def is good': True
Is 'ghi' in 'This string is abc': False
Is 'ghi' in 'This is a string': False
Is 'ghi' in 'This def is good': False
Is 'jkl' in 'This string is abc': False
Is 'jkl' in 'This is a string': False
Is 'jkl' in 'This def is good': False