如何将一个列表与一个句子进行匹配,并将单词列表与id words表单进行匹配

2024-09-22 20:30:45 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一堆身份证和他们的判决。我需要把这些数据和一个单词列表进行比较。 我希望我的输出是这样的:我从匹配单词列表的句子中获得ID和相应的单词

我试着在Excel中实现它们,将文本转换成列,然后转换列表,然后进行条件格式设置。但它真的不可能像一个句子,一次有这么多单词,而且有很多句子

有没有一种方法可以通过python编程来实现呢

输入:

 | ID | data                 |    | List |
 |----|----------------------| .   hello
 | 1  | hello can you hear me| .   love
 | 2  | roses are red        | .   water
 | 3  | water is life        | .   roses
 | 4  | pie                  | .   pie
 | 5  | I love chicken pie   | .   chicken
 |----|----------------------| .   hear
                                   red

预期输出:

 | ID | data   |
 |----|--------|
 | 1  | hello  |
 | 1  | hear   |
 | 2  | roses  |
 | 2  | red    |
 | 3  | water  |
 | 4  | pie    |
 | 5  | love   |
 | 5  | chicken|
 | 5  | pie    |

Tags: 数据idhello列表datared单词句子
1条回答
网友
1楼 · 发布于 2024-09-22 20:30:45

假设您有一个包含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

相关问题 更多 >