Python 程序从两个字符串中查找不常见的单词

pythonserver side programmingprogramming

在本文中,我们将了解下面给出的问题陈述的解决方案。

问题陈述 − 我们有两个字符串,我们需要从给定的字符串中获取不常见的单词。

现在让我们观察下面实现中的解决方案 −

示例

# 不常见的单词
def find(A, B):
   # count
   count = {}
   # insert in A
   for word in A.split():
      count[word] = count.get(word, 0) + 1
   # 插入 B
   for word in B.split():
      count[word] = count.get(word, 0) + 1
   # 返回 ans
   return [word for word in count if count[word] == 1]
# main
A = "教程点 "
B = "Python on Tutorials point"
print("字符串中不常见的单词是:",find(A, B))

输出

字符串中不常见的单词是:['Python', 'on']

所有变量均在本地范围内声明,其引用如上图所示。

结论

在本文中,我们了解了如何编写 Python 程序从两个字符串中查找不常见的单词


相关文章