【问题标题】:python if multiple string return the words that contains in the sentencespython如果多个字符串返回句子中包含的单词
【发布时间】:2018-08-20 09:21:22
【问题描述】:

我有一个单词列表,我想做 if 语句,下面是我的列表:

list = ['camera','display','price','memory'(will have 200+ words in the list)]

这是我的代码:

def check_it(sentences):
    if 'camera' in sentences and 'display' in sentences and 'price' in sentences:
        return "Camera/Display/Price"
    if 'camera' in sentences and 'display' in sentences:
        return "Camera/Display"
    ...
    return "Others"

h.loc[:, 'Category'] = h.Mention.apply(check_it)

这些组合会太多,而且我想让单词单独返回到行。 有谁知道如何制作这个样本并单独返回单词而不是“相机/显示器/价格”?

【问题讨论】:

  • 你的例子表达得不好。如果句子同时包含 'camera' 和 'display',那么如果还有 'price' 则不清楚应该发生什么,因为第二个 if 块永远不会被执行(已经从前一个块返回)。
  • 可能关键字最多的情况应该首先返回。
  • Category 中的类别是否按字母顺序排列?例如。 Camera/Price/Display 应该返回为 Camera/Display/Price?

标签: python pandas combinations matching


【解决方案1】:

通过正则表达式使用str.findall - 使用| 连接列表的所有值,最后一个str.join 值通过/

df = pd.DataFrame({'Mention':['camera in sentences and display in sentences',
                              'camera in sentences price']})


L = ['camera','display','price','memory']
pat = '|'.join(r"\b{}\b".format(x) for x in L)
df['Category'] = df['Mention'].str.findall(pat).str.join('/')
print (df)
                                        Mention        Category
0  camera in sentences and display in sentences  camera/display
1                     camera in sentences price    camera/price

另一种具有列表理解的解决方案,也适用于带有join 的列表使用生成器:

df['Category1'] = [[y for y in x.split() if y in L] for x in df['Mention']]
df['Category2'] = ['/'.join(y for y in x.split() if y in L) for x in df['Mention']]
print (df)
                                        Mention          Category1  \
0  camera in sentences and display in sentences  [camera, display]   
1                     camera in sentences price    [camera, price]   

        Category2  
0  camera/display  
1    camera/price  

【讨论】:

  • 结果给我 'camera/display/camera' 是 Mention 是 'camera in sentence, and display or camera in sentence.'你知道如何解决这个问题吗?我只想要一个相机结果
  • @Aimee - 在此处添加 apply(set) 喜欢 df['Category'] = df['Mention'].str.findall(pat).apply(set).str.join('/')
  • 对于另一个解决方案,请使用 df['Category1'] = [list(set([y for y in x.split() if y in L])) for x in df['Mention']]df['Category2'] = ['/'.join(set(y for y in x.split() if y in L)) for x in df['Mention']]
  • @Aimee - 如果我的回答有帮助,别忘了接受。要将答案标记为已接受,请单击答案旁边的复选标记以将其从空心切换为绿色 (see screenshot)。谢谢。
【解决方案2】:
some_words = ['camera','display','price','memory']
def check_it(sentences, words):
   find_words = []
   for word in words:
      if word in sentences:
         find_words.append(word)
   return find_words
t = check_it('display has camera and price is', some_words)
print t

【讨论】:

    【解决方案3】:

    为什么不检查每个句子中的单词?

    wordsList = ['camera','display','price','memory'(will have 200+ words in the list)]
    
    def check_it(sentence, wordsList):
        wordString = ''
        flag = False
        counter = 0
        for word in sentence.split():
            if word in wordsList:
                if counter != 0:
                    wordString = wordString + '/' + word
                else:
                    wordString = word
                flag = True
                counter += 1
        if flag:
            return wordString
        elif not flag:
            return 'Others'
    

    【讨论】:

    • result 只会返回'other',不返回列表中的单词
    • 我刚刚编辑了它。我添加了 sentence.split() 是因为在它检查每个字符而不是每个单词之前。
    猜你喜欢
    • 1970-01-01
    • 2013-04-11
    • 1970-01-01
    • 2016-12-06
    • 1970-01-01
    • 2017-02-28
    • 2017-04-27
    • 2014-05-20
    • 2017-08-27
    相关资源
    最近更新 更多