1 回答

TA贡献1906条经验 获得超10个赞
假设您有一个包含 ID 和句子的 csv 表sentences.csv,以及一个包含单词列表的文本文件words.txt,您可以执行以下操作:
import csv
words = set(l.strip() for l in open('words.txt'))
table = []
with open('sentences.csv') as f:
for sid,sentence in csv.reader(f):
table += [[word, sid] for word in sentence.split() if word in words]
csv.writer(sys.stdout).writerows(table)
这是表达这一点的紧凑方式,并且在错误检查方式中没有做太多事情。例如,如果 csv 文件中的某些行中没有 2 个单元格,则循环将崩溃。更简单地说,可以将表解析表示为:
table = [[word,sid] for sid,sentence in csv.reader(open('sentences.csv'))
for word in sentence.split() if word in words]
两者都给出了预期的输出
hello,1
hear,1
roses,2
red,2
water,3
pie,4
love,5
chicken,5
pie,5
添加回答
举报