0

是否可以在字符串中找到一个值,其中该值是 CSV 中的任何字段值之一。例如..

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
     ....

干杯,

4

3 回答 3

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
于 2012-10-01T15:43:49.587 回答
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
于 2012-10-01T15:56:51.290 回答
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

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

于 2012-10-01T15:49:23.307 回答