繁体   English   中英

如何在两个大的csv文件中找到字符串中的子字符串(Python)

[英]How to find a substrings in string in two big csv file (python)

我有两个很大的csv文件。 主要的有一个字段作为产品名称,在其他csv文件中,我有一些关键字。 我正在第一个CSV文件的产品名称中寻找这些关键字。 目前,我的代码是这样的:

class Keyword:
    # keyword class for adding match keywords
        def __init__(self):
          self.data={}
        def add(self, keyword, count):
          if keyword in self.data.keys():
            self.data[keyword]+=count
          else:
            self.data[keyword]=count
        def get_match(self):
           temp = []
           for key, value in self.data.iteritems():
              temp.append(key)
              temp.append(value)
           return temp

for i, product_row in product_df.iterrows():
    product_title = product_row['title'].lower().replace(',','')
    k = Keyword()
    for j, keyword_row in keyword_df.iterrows():
        if keyword_row['keyword'] in product_title:
           k.add(keyword_row['keyword'], keyword_row['count'])

    match_items = k.get_match()
    if len(match_items)>0:
        temp = product_row.tolist()
        temp = [str(x).replace(',','') for x in temp]
        temp.extend(match_items)
        print>>sys.stdout, str(temp).strip('[]').replace("'",'')
    else:
        pass

这段代码非常慢,我有许多这样的csv文件应该相互比较。 您知道比较这些文件的更有效方法吗?

如果您的关键字实际上是单个单词,而不是多单词表达式,我的第一个建议是将产品标题转换为一组,以加快查找速度:

product_title = set(product_row['title'].lower().replace(',','').split())

阅读整个关键字文件,将关键字存储在列表中。 之后,请阅读您的产品字段,并检查该字段中是否包含任何关键字,然后打印出来。

with open("keywords.txt", "r") as f:
    keywords = f.read().splitlines()

with open("products.txt") as f:
    for product_name in f:
        if any(keyword in product_name for keyword in keywords):
            print product_name

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM