Question

In Python 3 only please. A simple function that will be used on a file.

commonpair(str) – Takes a single string argument, representing the first word. This function should return the word that most frequently followed the given argument word (or one of, in case of ties). If the argument word does not appear in the text at all, or is never followed by another word (i.e., is the last word in the file), this function should return None.

I did the code but it does not do what's mentioned.

#Commonpair method
def commonpair(str):

   inp = " "
  
   wordsfreq = {}
   pair = {}
  
   for line in words:
       #Add them
       inp += line + " "
   for line in words:
      
       split = line.split(" ")
      
       for word in split:
      
           if word.lower() not in wordsfreq.keys():
          
               wordsfreq[word.lower()] = 1
              
           else:
          
               #Increae it
               wordsfreq[word.lower()] += 1
      
   fIndex = inp.find(str)
      
   if(fIndex == -1):
       return None
      
   # What remains
   text = inp[(fIndex + len(str)):]
      
   split = text.split(" ")
  
   wordsfreq.pop(str, None)
  
   for word in wordsfreq.keys():
  
       count = 0
      
       for topword in split:
           if topword == word:
               count += 1
      
       pair[word] = count
      
      
   keys = list(pair.keys())
   values = list(pair.values())
   maxWord = keys[values.index(max(values))]


   return maxWord

#Note Words is a list in load() method


   Getting common pair for apple pear Getting common pair for pear apple Getting common pair for banana apple Getting common

Input text (a file):
banana peach coconut peach pear banana peach apple peach pear apple coconut apple coconut peach pear apple apple peach pear pear apple banana banana banana banana coconut pear apple peach peach apple peach pear coconut apple apple coconut banana peach pear pear apple pear apple pear banana peach coconut apple coconut

0 0
Add a comment Improve this question Transcribed image text
Answer #1

Python 3.6.1 (default, Dec 2015, 13:05:11) [GCC 4.8.2] o main.py Commonpair method def commonpair (lastWord) global words fre

# first read the words from file.

wordsfreq = {}

# change below for the name of your file
for line in open('data.txt'):
        for w in line.split(" "):
                w = w.lower()
                wordsfreq[w] = wordsfreq.get(w, 0) + 1

# now our dictionary is ready.
print('Frequency of words: ')
print(wordsfreq)



#Commonpair method
def commonpair(lastWord):
        global wordsfreq

        # we need to find the word which occurs most frequenctly after last one.
        if lastWord not in wordsfreq:
                return None
        
        lastFreq = wordsfreq[lastWord]

        # now find words having more freq than this, or ties
        higherFreq = {k: v for k, v in wordsfreq.items() if v <= lastFreq and k != lastWord}
        print(higherFreq)

        if len(higherFreq) == 0:
                return None

        # from above dictionary, just take the word with minimum freq
        return max(higherFreq.keys(), key=lambda k: higherFreq[k])

print(commonpair('apple'))
print()
print(commonpair('pear'))
print()
print(commonpair('banana'))
print()
print(commonpair('orange'))

please try above code.. although the code output do not match the expected output exactly.. But i have coded it very cleanly.. it seems there is some issue in the input file.. Let me know if any issues.

Add a comment
Know the answer?
Add Answer to:
In Python 3 only please. A simple function that will be used on a file. commonpair(str)...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • (Python 3) Write a program that reads the contents of a text file. The program should...

    (Python 3) Write a program that reads the contents of a text file. The program should then create a dictionary in which the keys are individual words found in the file and the values are the number of times each word appears and a list that contains the line numbers in the file where the word (the key) is found. Then the program will create another text file. The file should contain an alphabetical listing of the words that are...

  • In python Count the frequency of each word in a text file. Let the user choose...

    In python Count the frequency of each word in a text file. Let the user choose a filename to read. 1. The program will count the frequency with which each word appears in the text. 2. Words which are the spelled the same but differ by case will be combined. 3. Punctuation should be removed 4. If the file does not exist, use a ‘try-execption’ block to handle the error 5. Output will list the words alphabetically, with the word...

  • Please do the following project in C++ programming language. You can use a bag to create...

    Please do the following project in C++ programming language. You can use a bag to create a spell checker. The bag serves as a dictionary and contains a collection of correctly of correctly spelled workds. To see whether a word is spelled correctly, you see whether it is contained in the dictionary. Use this scheme to create a spell checker for the words in an external file. To simplify your task, restrict your dictionary to a manageable size. The dictionary...

  • Using Python, if you could help me with the code # Create a modified version of the search linear function defined # above to return all # occurrences of the search word in the text # An occurrence is...

    Using Python, if you could help me with the code # Create a modified version of the search linear function defined # above to return all # occurrences of the search word in the text # An occurrence is the index of a word in the text that matches your given # search string. # e.g. if "hatter" occurs at positions 0, 6, 12 then return [ 0, 6, 12] def search_linear_occurrences(xs, target): """ Find and return a list of...

  • python please 11 def add_item(items, word): 14 15 16 F # check if the word is...

    python please 11 def add_item(items, word): 14 15 16 F # check if the word is in the dictionary (keys of dictionary) if word in items: items [word] = items (word] + 1 # update the count else: # word is not in dictionary items[word] = 1 # add the word with count 1 return items [word] # return the current count of word after updation Create a function named build_dictionary that takes a list of words (as a parameter)...

  • Using Python, if you could help me with the code # Create a modified version of...

    Using Python, if you could help me with the code # Create a modified version of the search linear function defined # above to return all # occurrences of the search word in the text # An occurrence is the index of a word in the text that matches your given # search string. # e.g. if "hatter" occurs at positions 0, 6, 12 then return [ 0, 6, 12] def search_linear_occurrences(xs, target): """ Find and return a list of...

  • I need only one  C++ function . It's C++ don't write any other language. Hello I need...

    I need only one  C++ function . It's C++ don't write any other language. Hello I need unzip function here is my zip function below. So I need the opposite function unzip. Instructions: The next tools you will build come in a pair, because one (zip) is a file compression tool, and the other (unzip) is a file decompression tool. The type of compression used here is a simple form of compression called run-length encoding (RLE). RLE is quite simple: when...

  • Help me with this Python Question a. build_word_dictionary (filename) – This builds a word dictionary indexed...

    Help me with this Python Question a. build_word_dictionary (filename) – This builds a word dictionary indexed by words from the file who’s filename is provided as an argument. It uses the words as keys and the count of occurrences as values. It returns the dictionary it constructed. It can use the ‘tokenize()’ function that is provided in the lecture slides. b. inverse_dict(dict) – This method takes a dictionary (generated by build_word_dictionary() and inverts it (as was done with students and...

  • In this assignment, you will explore more on text analysis and an elementary version of sentiment...

    In this assignment, you will explore more on text analysis and an elementary version of sentiment analysis. Sentiment analysis is the process of using a computer program to identify and categorise opinions in a piece of text in order to determine the writer’s attitude towards a particular topic (e.g., news, product, service etc.). The sentiment can be expressed as positive, negative or neutral. Create a Python file called a5.py that will perform text analysis on some text files. You can...

  • Overview: file you have to complete is WordTree.h, WordTree.cpp, main.cpp Write a program in C++ that...

    Overview: file you have to complete is WordTree.h, WordTree.cpp, main.cpp Write a program in C++ that reads an input text file and counts the occurrence of individual words in the file. You will see a binary tree to keep track of words and their counts. Project description: The program should open and read an input file (named input.txt) in turn, and build a binary search tree of the words and their counts. The words will be stored in alphabetical order...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT