Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
4.4k views
in Technique[技术] by (71.8m points)

python - Finding common words in two dictionaries

I have 2 different dictionaries (book1words and book2words) and words in it. Some words are the same in both dictionaries and some are not. I have to find the common words in these dictionaries and print them in the number of words the USER WANTS to see. However, I have to specify the number of times the common word occurs in 1st dictionary and 2nd dictionary, and lastly, how many times it occurs in total.It must be from most repetitive to least repetitive. We can not use any special library for python like collections or counter.Output should be like this:

Common word         frequent1         frequent2            frequentsum
1.print                20                 19                    39
2.number               10                  8                    18
3.program              5                   7                    12             

Here is what I've tried:

book1words_book1 = {}
for word in replacingpunctuations_book1:
    if word not in book1words_book1:
        book1words_book1[word] = 1
    else:
        book1words_book1[word] += 1
book2words = {}
for word in replacingpunctuations_book2:
    if word not in book2words:
        book2words[word] = 1
    else:
        book2words[word] += 1

commonwords={}
for word in book1words_book1:
    if word in  book2words:
        commonwords[word]=1
    else:
        commonwords[word] +=1

commonwords = sorted(commonwords.items(), key=lambda x: x[1], reverse=True)
z = int(input("How many words that you want to see?"))
print(" WORDCOMMON  FREQUENCY")
for k, v in commonwords[:z]:
    print(k, v)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Assuming you have two list of words, book1WordList and book2WordList

your can define your counter method as

def mycounter(list):
  mydict = {}
  key_val = 1
  for i in list:
    if i in mydict:
      mydict[i]=mydict[i]+1
    else:
      mydict[i]=key_val
  return mydict

book1WordList = ['jungle','forest','jungle','hi']
book2WordList = ['hi','hello','hello','forest','hi','hello','forest']


book1dict = mycounter(book1WordList)
book2dict = mycounter(book2WordList)

book1keyslist = list(book1dict.keys())
book2keyslist = list(book2dict.keys())
book1set = set(book1keyslist)
commankeys = book1set.intersection(book2keyslist)
for i in commankeys:
  print (f"{i}   {book1dict[i]}  {book2dict[i]}")

Output:

forest   1   2
hi       1   2

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...