遍历csv列中一行的所有元素以捕获存在的所有实体

时间:2019-02-11 23:37:19

标签: python csv iterator row

我想捕获csv文件列中存在的所有行的所有字符串。目前,仅捕获了第一个字符串,但我想获取该行中存在的所有字符串。 现在的问题是'product'变量仅给出产品名称的第一个字符串,因此对于第二种情况(ABC2,ABC3,BCA3),仅csv中将添加ABC2,而其他两个名称将被忽略,但是我要添加所有元素。我如何遍历此行,以便添加所有元素,我将发布代码示例和csv供参考:

import spacy
import re
import csv
from spacy.matcher import PhraseMatcher

#Function to convert PhraseMatcher return value to string indexes 
def str_index_conversion(lbl, doc, matchitem):
    o_one = len(str(doc[0:matchitem[1]]))
    subdoc = doc[matchitem[1]:matchitem[2]]
    o_two = o_one + len(str(subdoc))
    return (o_one, o_two, lbl)

#nlp = spacy.blank('en')
nlp = spacy.load('en')

if 'ner' not in nlp.pipe_names:
    ner = nlp.create_pipe('ner')
    nlp.add_pipe(ner)
else:
    ner = nlp.get_pipe('ner')

ner.add_label('PRODUCT')     

DIR = 'C:\\Users\\Lenovo\\.spyder-py3\\smoke\\'
matcher = PhraseMatcher(nlp.vocab)


list_str_index = []
to_train_ents = []
with open('names.csv', newline='') as myFile:

    reader = csv.reader(myFile)
    for row in reader:
        try:
            product = row[0].lower()
            filename = row[1]
            file = open(DIR+filename, "r", encoding ='utf-8')
            #print(file)
            filecontents = file.read()
            for s in filecontents:
                filecontents = re.sub(r'\s+', ' ', filecontents)
                #filecontents = filecontents.encode().decode('unicode-escape')
                filecontents = ''.join([line.lower() for line in filecontents])
                matcher.add('PRODUCT', None, nlp(product))
                doc = nlp(filecontents)
                matches = matcher(doc)
                        #print(matches)
                list_str_index = [str_index_conversion('PRODUCT', doc, x) for x in matches]
                to_train_ents.append((filecontents, dict(entities=list_str_index)))
                break


        except Exception as e:
            #print(e)
            pass```


SAMPLE CSV:

PRODUCT          FILES
ABC              XXXX
ABC2, ABC3, BCA3 XXXX
BC2              XXXX```




0 个答案:

没有答案