首页 > 解决方案 > 如何不完全匹配 2 个 csv 文件

问题描述

我有 2 个 csv 文件,dictionary.csv 和 file.csv,我想检查 dictionary.csv 中的单词是否存在于 file.csv 中。dictionary.csv 中的某些行包含超过 2 个单词,我想知道是否有办法做到这一点,

如果该行中有 3 个单词,并且 file.csv 中匹配的行中至少有 2/3 个单词,则返回 1,否则返回 0

如果该行中有 2 个单词,并且 file.csv 中匹配的行中至少有 1/2 个单词,则返回 1,否则返回 0

到目前为止,以下是我的代码,它正在精确匹配

file=pd.read_csv("file.csv")
dictionary=pd.read_csv("dictionary.csv")

pattern='|'.join(dictionary)

news["contain diseases1"] = np.where(
    news["STORY"].str.contains(pattern, na=False),
    1, 0
)

news.to_csv("clues.csv")

为了进一步帮助您理解我的问题,以下是 dictionary.csv 和 file.csv 的内容

dictionary.csv

sigmoid colon cancer
site specific early onset breast cancer syndrome
skin cancer
file.csv

id   STORY
0    Ari have a colon cancer
1    Cancer is an epidemic
2    Breast cancer can happen to both genders

我应该从这些文件中得到的输出是

clue.csv
id   STORY                                      contain diseases1
0    Ari have a colon cancer                         1
1    Cancer is an epidemic                           1
2    Breast cancer can happen to both genders        1
3    Prioritizing the health of skin                 0
4    A specific camping site is only for early birds 0

截至目前,由于我现在拥有的代码是完全匹配的,所以我继续得到 0

标签: python-3.xpandascsvdictionary

解决方案


你考虑过fuzzywuzzy python 库吗?它是一个由 SeatGeek 开源的字符串匹配库。它根据不完美匹配提供匹配分数,然后您决定哪个阈值足够接近以成为匹配。

根据我的经验,我用它来匹配来自不同数据源的医生姓名(例如,有人说“Dr.”,有人说“MD”,一些名字是收缩的,一些姓氏因未婚姓而改变)。

这是图书馆的 2 个链接。

https://chairnerd.seatgeek.com/fuzzywuzzy-fuzzy-string-matching-in-python/

https://github.com/seatgeek/fuzzywuzzy


推荐阅读