Python 3.x 将列表中的字符串匹配到CSV文件Python的行
我的目标是编写一个迭代CSV文件的函数,并实现以下功能:Python 3.x 将列表中的字符串匹配到CSV文件Python的行,python-3.x,loops,csv,Python 3.x,Loops,Csv,我的目标是编写一个迭代CSV文件的函数,并实现以下功能: 获取“关键字”,该关键字是字符串列表,并返回描述中包含“关键字”的所有关联代码 CSV文件格式示例: def find_that_code(keywords): codelist = [] keywords = str(keywords) with open('codes.csv') as csv_file: reader = csv.reader(csv_file, delimiter=',') next(rea
- 获取“关键字”,该关键字是字符串列表,并返回描述中包含“关键字”的所有关联代码
def find_that_code(keywords):
codelist = []
keywords = str(keywords)
with open('codes.csv') as csv_file:
reader = csv.reader(csv_file, delimiter=',')
next(reader) # skip the first row
for row in reader:
if row[3] == any([x in keywords for x in keywords]):
code = row[0]
return True
else:
return False
“2399”、“1”、“偷自行车”、“偷自行车”
例如:
def find_that_code(keywords):
codelist = []
keywords = str(keywords)
with open('codes.csv') as csv_file:
reader = csv.reader(csv_file, delimiter=',')
next(reader) # skip the first row
for row in reader:
if row[3] == any([x in keywords for x in keywords]):
code = row[0]
return True
else:
return False
def find_that_code(keywords):
codelist = []
keywords = str(keywords)
with open('codes.csv') as csv_file:
reader = csv.reader(csv_file, delimiter=',')
next(reader) # skip the first row
for row in reader:
if row[3] == any([x in keywords for x in keywords]):
code = row[0]
return True
else:
return False
目前,我有返回真或假代码,以找出我的问题所在。但是,一旦我知道如何将关键字列表中的字符串与CSV的第[3]行相匹配,那么我就应该能够完成它的其余部分
感谢您抽出时间,我非常感谢您的建议。如果您希望查找描述列中出现任何给定关键字的所有行:
def find_that_code(keywords):
codelist = []
with open('codes.csv') as csv_file:
reader = csv.reader(csv_file, delimiter=',')
next(reader) # skip the first row
for row in reader:
if any(k in row[3].lower() for k in keywords):
codelist.append(row[0])
return codelist
我试着尽可能少地改变你原来的帖子。但是请注意,这将根据您尝试执行的操作而非常缓慢,因为如果您多次调用它,您将从一开始就重复读取该文件,并针对您希望匹配的每个关键字集重新处理它
如果您希望定期在此数据集上执行此操作,则最好将您的数据集转储到Solr或Lucene(或某种基于文本的搜索引擎)中。您希望此操作做什么
row[3]==any([x in关键字对应x in关键字])
?row[3]==any([x in关键字对应x in关键字])我对这段代码的意图是,每当描述(出现在第[3]行)与关键字匹配时,它都会返回true并继续为该行添加关联的代码。我想你的意思是any(第[3]行中的k)。关键字中的k的下限())
在这种情况下使用防护没有多大意义。啊,是的,肯定更好。抱歉,我刚刚才意识到我的问题可能有点被误解了。如果关键字出现在“描述”列的任何位置,则您提供的函数将返回所有代码。但是,我不知道只有当关键字出现在同一行时,如何返回代码。