【问题标题】:Search for words inside a csv based on a dictionary根据字典在 csv 中搜索单词
【发布时间】:2021-05-19 09:45:28
【问题描述】:

假设我有一个字典 csv,例如:

fruit   vegetable   meat
banana  broccoli    beef
apple   carrot      chicken
orange  corn        pork
mango   NaN         NaN
coconut NaN         NaN

还有另一个 csv,例如:

sentences
Today I ate some beef.
Corn is tasty.
I drank some coconut water.

我正在尝试将句子 csv 中的字符串与字典中的字符串进行匹配,以进行如下分类:

sentences                   food  
Today I ate some beef.      meat 
Corn is tasty.              vegetable
I drank some coconut water. fruit

我需要做什么才能产生该输出?我应该消除 NaN 以使其正常工作还是可以忽略它们?

【问题讨论】:

  • 如果一个句子包含属于多个列的单词,如何分类?
  • 我也在寻找解决方案,但目前我还不知道。

标签: python string dictionary search string-matching


【解决方案1】:

许多方法可以做你想做的事。这是一个嵌套的 for 循环。我很确定您可以执行递归方法甚至列表推导。

fruit = ["banana","apple",...]
meat = ["beef","chicken",...]
vegetable = ["corn","brocolli"] #Nan will simply be ignored
classes = [fruit,meat,vegtable]
#Now you have your 'classes' of strings.

sentences = ["Today I ate some beef.",...]#Here are your list of sentences.
output = []
for sentence in sentences: #for each sentence
   for food_type in classes: # we check if it exists in each class
       for food in food_type: # we check each food of each class
           if food in sentence: #if that string is in the sentence we pair it into a tuple
               output.append((sentence,food_type))
               

仅当字符串准确时才匹配(大小写很重要)。并且有一些警告可能会出现错误的类,例如如果你有“straw”和“strawberry”。

还可以查看此link 以将您的 csv“读取”到列表中。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-04-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-03-19
    • 1970-01-01
    相关资源
    最近更新 更多