【问题标题】:Find list of keywords in string在字符串中查找关键字列表
【发布时间】:2013-09-06 14:48:05
【问题描述】:

所以我有一个关键词列表,我正在尝试检查是否在我的 csv 表的一行中找到了这些词,如果存在,它应该被标记。我的代码运行良好,除非该行包含多个关键字,否则不会被标记。想法?

import sys
import csv
nk = ('aaa','bbb','ccc')
with open(sys.argv[1], "rb") as f:
    reader = csv.reader(f, delimiter = '\t')
    for row in reader:
        string=str(row)
        if any(word in string for word in nk):
            row.append('***')
            print '\t'.join(row)
        else:
            print '\t'.join(row)

提前致谢!

【问题讨论】:

    标签: python string list csv


    【解决方案1】:

    使用集合交集获取所有常用词:

    nk = {'aaa','bbb','ccc'}
    seen = set()             #keep as track of items seen so far in this set
    with open(sys.argv[1], "rb") as f:
        ...
        for row in reader:
            #update `seen` with the items found common between `nk` and the current `row`
            seen.update(nk.intersection(row))
        ...
    

    不要将row 转换为字符串(string=str(row)),in 运算符也适用于列表,其行为与字符串的 in 不同:

    >>> strs = "['foo','abarc']"
    >>> 'bar' in strs            #substring search
    True
    >>> lis = ['foo','abarc']    #item search
    >>> 'bar' in lis
    False
    

    【讨论】:

    • 我正在转换为字符串,因为我的一些列表项是“部分关键字”。例如一行可能包含 ['aaaaaaaaaaaa', 'xxxxx', ,'yyyyyy'] 如果我不转换为字符串,in 运算符将错过 'aaaaaaaaaa'
    • @AishaAJ 为此你可以使用matches = [x for x in nk if any(x in item for item in row)]
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-10-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-05-16
    相关资源
    最近更新 更多