猿问

如何将一个列表与一个句子匹配并带上带有 id - words 格式的单词列表

我有一堆身份证和他们的句子。我需要将此数据与单词列表进行比较。我希望我的输出能够从与单词列表匹配的句子中获取 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    |


皈依舞
浏览 189回答 1
1回答

隔江千里

假设您有一个包含 ID 和句子的 csv 表sentences.csv,以及一个包含单词列表的文本文件words.txt,您可以执行以下操作:import csvwords = 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,1hear,1roses,2red,2water,3pie,4love,5chicken,5pie,5
随时随地看视频慕课网APP

相关分类

Python
我要回答