📌  相关文章
📜  Python程序从两个字符串中查找不常见的单词

📅  最后修改于: 2021-04-22 01:21:44             🧑  作者: Mango

给定两个句子作为字符串AB。任务是返回所有不常见单词的列表。如果一个单词在任一句子中恰好出现一次,而在另一个句子中没有出现,则是不常见的。

注意:句子是由空格分隔的单词的字符串。每个单词仅包含小写字母。

例子

Input : A = "Geeks for Geeks" 
        B = "Learning from Geeks for Geeks"
Output : ['Learning', 'from']

Input : A = "apple banana mango" 
        B = "banana fruits mango"
Output : ['apple', 'fruits']

方法:每个不常见的单词在任何一个字符串出现一次。因此,我们进行哈希处理以计算每个单词出现的次数,然后返回恰好出现一次的单词列表。

下面是上述方法的实现:

# Python3 program to find a list of uncommon words
  
# Function to return all uncommon words
def UncommonWords(A, B):
  
    # count will contain all the word counts
    count = {}
      
    # insert words of string A to hash
    for word in A.split():
        count[word] = count.get(word, 0) + 1
      
    # insert words of string B to hash
    for word in B.split():
        count[word] = count.get(word, 0) + 1
  
    # return required list of words
    return [word for word in count if count[word] == 1]
  
# Driver Code
A = "Geeks for Geeks"
B = "Learning from Geeks for Geeks"
  
# Print required answer
print(UncommonWords(A, B))
输出:
['from', 'Learning']


解决此问题的另一种方法:

def uncommon(a,b):
    list_a = a.split()
    list_b = b.split()
    uc = ''
    for i in list_a:
        if i not in list_b:
            uc = uc+" "+i
    for j in list_b:
        if j not in list_a:
            uc = uc+" "+j
  
    return uc
  
# Driver code
a = "apple banana mango"
b = "banana fruits mango"
print(uncommon(a,b))
输出:
['apple','fruits']

另外一种使用内置函数“ symmetric_difference()”的方法

def uncommon(a,b):
  a=a.split()
  b=b.split()
  k=set(a).symmetric_difference(set(b))
  return k
  
#Driver code
if __name__=="__main__":
  a="apple banana mango" 
  b="banana fruits mango"
  print(list(uncommon(a,b)))
输出:
['apple', 'fruits']

解决这个问题的另一种方法

def uncommon(A, B):
    un_comm = [i for i in "".join(B).split() if i not in "".join(A).split()]
    return un_comm
  
#Driver code
A = "Geeks for Geeks" 
B = "Learning from Geeks for Geeks"
print(uncommon(A, B))
输出:
['Learning', 'from']