繁体   English   中英

列出 Python 中两个列表中不匹配的单词

[英]List mismatched words from two lists in Python

我想打印两个句子中都不存在的单词,如果一个单词在第一个句子中出现两次但在第二个句子中只出现一次,我也想打印那个单词。 例如:

a = "The winter winter season is cold"
b = "The summer winter season is hot"

Output: {'winter','cold','summer','hot'}

我尝试在 python 中使用 Set 但它给了我这个 output: {'hot', 'cold', 'summer'}

def uncommonwords(a,b):
    listA = a.split()
    listB = b.split()
    listC = listA +listB
    return set(listC) - set(listA).intersection(listB)
print(uncommonwords(a,b))

发生的事情是:

  1. 您将列表转换为集合,这会导致删除重复的单词。 winter在listA中只出现一次)
  2. 由于冬天出现在一组而不是另一组中,因此它没有被显示。

您需要额外的单词列表,这些单词在a中出现两次,在b中出现一次。 当您使用集合时,您会丢失句子中的单词数。 因此,您可以使用 dict 代替:

dictA = {x:a.count(x) for x in a.split()}
dictB = {x:b.count(x) for x in b.split()}

[x for x in dictA.keys() if dictA[x]==2 and dictB[x]==1] 

Output

['winter']

您可以将整个 function 压缩成

[x for x in dictA.keys() if (x not in dictB.keys()) or (dictA[x]==2 and dictB[x]==1)] + [x for x in dictB.keys() if (x not in dictA.keys())]

Output

['winter', 'cold', 'summer', 'hot']

只需使用“集合”package

from collections import Counter
a = "The winter winter season is cold" 
b = "The summer winter season is hot"

def uncommonwords(a,b):
  listA = Counter(a.split())
  listB = Counter(b.split())

  return list((listA - listB) + (listB - listA))

print(uncommonwords(a,b))

你的 output 将是

['winter', 'cold', 'summer', 'hot']

在这种情况下,我们使用每个单词的计数器并操纵列表和获取结果的差异

你也可以试试这个。

a = "The winter winter season is cold"
b = "The summer winter season is hot"


def uncommonwords(a, b):
    a = a.split()
    b = b.split()
    h = set([x for x in a if a.count(x) > 1] + [x for x in b if b.count(x) > 1])
    k = set(a).symmetric_difference(set(b))
    return set.union(k, h)


print(uncommonwords(a, b))

或者如果你有iteration_utilities实用程序而不是set([x for x in a if a.count(x) > 1] + [x for x in b if b.count(x)你可以set(list(duplicates(a)) + list(duplicates(b)))

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM