Monday, October 15, 2018

Movie Sentiment Analysis (Java)

Sentiment Analysis Background


Sentiment analysis is the process of using software to classify a piece of text into a category that reflects the opinion of the writer. Sentiment analysis falls into the growing field of machine learning. In this assignment, you will be writing a simple sentiment analysis program to predict the score a movie reviewer would give based on the words that they use.
 

Sentiment Analysis Algorithm

The goal of your program is to use a data set of known reviews to predict the review for a new piece of text. Our algorithm for sentiment analysis is a simple one: For each word in the input text, calculate the average score of the reviews that use that word per word use. (For the sake of clarity, let’s call that score the “word score”) Then, find the averages of the word scores for the words in your input review. That number is your predicted score for the input text. You should ignore capitalization 
and punctuation.
 

For example, let’s say we have two reviews:

Score: 1, Text: “The plot holes were the most outrageous I’ve ever seen.”
Score: 4, Text: “The outrageous slapstick sequences left me howling.”
In this example, “Outrageous” is used once in a 1 score review and once in a 4 score review. That means that its word score is 2.5. “The” is used twice in a 1 score review and once in a 4 score review, meaning that its word score is 2. If our input text was just “the outrageous,” we would predict a score of 2.25.



Code:


Caution: please change the file directory before running.

MovieApp.java

import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Scanner;

public class MovieApp {


    public static void main(String[] nt) throws IOException {

        HashMap<String, Word> wordHashMap = new HashMap<>();
        FileReader in = null;
        Scanner scanner = new Scanner(System.in);
        StringBuffer stringBuffer = new StringBuffer();


        while (true) {



            System.out.println("Review filename?");
            String fileName = scanner.nextLine();


            try {
                in = new FileReader("/Users/mrdishant/Assignment Java/src/" + fileName);


                int c;
                while ((c = in.read()) != -1) {
                    stringBuffer.append((char) c);
                }

            } catch (FileNotFoundException e) {
                System.out.println("Please Enter a valid fileName.");
//                e.printStackTrace();                continue;
            } catch (IOException e) {
                System.out.println("Please Enter a valid fileName.");
//                e.printStackTrace();                continue;
            } finally {
                if (in != null) {
                    in.close();
                }
            }


            try {

                String[] lines = stringBuffer.toString().toLowerCase().split("\n");

                for (String line : lines) {

                    String[] words = line.replaceAll("\\p{Punct}", "").split(" ");


                    double score = Double.parseDouble(words[0]);

                    for (int i = 1; i < words.length; i++) {

                        if (wordHashMap.containsKey(words[i].trim())) {
                            wordHashMap.get(words[i].trim()).scores.add(score);

                        } else {
                            Word word1 = new Word();
                            word1.word = words[i].trim();

                            word1.scores = new ArrayList<>();
                            word1.scores.add(score);

                            wordHashMap.put(words[i].trim(), word1);
                        }
                    }

                }

            } catch (Exception e) {

                System.out.println("File doesn’t match the input structure please try again.");

                stringBuffer.delete(0,stringBuffer.length());

                continue;
            }



            System.out.println("Input review?");
            String inputReview = scanner.nextLine();

            String[] wordsInput = inputReview.trim().toLowerCase().split(" ");



            double sum = 0;

            for (String wInput : wordsInput) {

                wInput=wInput.trim();



                if (wordHashMap.containsKey(wInput)) {
                    wordHashMap.get(wInput).calculateScore();
                    sum += wordHashMap.get(wInput).wordScore;
                }

            }



            if (wordsInput.length > 0 && sum != 0.0) {

                double average = sum / wordsInput.length;

                System.out.println("" + Math.round(average * 100.0) / 100.0);

                break;

            } else {
                System.out.println("-1");
                break;
            }


        }
////        Word the=wordHashMap.get("1");//        the.calculateScore();//        System.out.print(the.toString());
////        for (Word word:wordHashMap.values()){//            word.calculateScore();//            //System.out.println(word.toString());//        }
        //System.out.println("Size "+hashMap.values().size());

//        for (String s:words)//            System.out.println("Words are "+s);
    }


}

Word.java


import java.util.ArrayList;

public class Word {

    String word;
    ArrayList<Double> scores;
    double wordScore;


    @Override    public String toString() {
        return "Word{" +
                "word='" + word + '\'' +
                ", scores=" + scores +
                ", wordScore=" + wordScore +
                '}';
    }

    public void calculateScore(){

        double sum=0.0;

        for (Double score : scores){
            sum+=score;
        }

        wordScore=sum/scores.size();

        wordScore=Math.round(wordScore * 100.0) / 100.0;

    }

}


Output:




Github repo url : https://github.com/mrdishant/Movie-Sentiment-Analysis-Java/tree/master/src

 




Wednesday, October 10, 2018

CD Store Management Python (Simple Approach)

ScreenShots :


Code:

listCD=[]

def sortByIndex(index):
for i in range(0,len(listCD)):
for j in range(0,len(listCD)-i-1):
if(listCD[j][index]>listCD[j+1][index]):
temp=listCD[j][index]
listCD[j][index]=listCD[j+1][index]
listCD[j+1][index]=temp

def createDatabase():
f=open("CD_Store.txt","r+")
for f1 in f.readlines():
try:
price=float(f1.split(",")[3])
except Exception as e:
print("Error in price ",e)
pass
listCD.append([f1.split(",")[0],f1.split(",")[1],f1.split(",")[2],price])

def printList():
for cd in listCD:
print(cd,"\n")

def findByTitle(target):
for cd in listCD:
if(target.lower() in cd[0].lower()):
print(cd)

def findByGenre(target):

for cd in listCD:
if(target.lower() in cd[2].lower()):
print(cd)

def findByArtist(target):
for cd in listCD:
if(target.lower() in cd[1].lower()):
print(cd)

def findByPrice(targetPrice):
for cd in listCD:
if(cd[3]<=targetPrice):
print(cd)

def main():
createDatabase()

while(True):
print("\nPlease Choose from below \n" )

print("1 to Print List of CDs")

print("2 to Sort CDs by Title")

print("3 for Sort CDs by Artist")

print("4 for Sort CDs by Genre")

print("5 for Sort CDs by Price")

print("6 for Find All CDs by Title")

print("7 for Find All CDs by Artist")

print("8 for Find All CDs by Genre")
print("9 for Find All CDs with Price at Most X")
print('quit to quit\n')


i=input()

if(i=='1'):
printList()
elif (i=='2'):
sortByIndex(0)
elif (i=='3'):
sortByIndex(1)
elif (i=='4'):
sortByIndex(2)
elif (i=='5'):
sortByIndex(3)
elif (i=='6'):
findByTitle(input("Enter CD Title : "))
elif (i=='7'):
findByArtist(input("Enter Artist name : "))
elif (i=='8'):
findByGenre(input("Enter Genre : "))
elif (i=='9'):
findByPrice(float(input("Enter target Price : ")))
elif (i.lower()=='quit'):
break

main()

Monday, October 8, 2018

CD Store Management System Python

Assignment:





Function SortByArtist

Input: List of CDs Output: Updates the list of CDs so that elements are sorted in ascending order by artist.
Description: Program sorts the list CDs by the artist attribute. 

Function SortByPrice 


Input: List of CDs Output: Updates the list of CDs so that elements are sorted in ascending order by price.
Description: Program sorts the list of CDs by the price attribute. Function 

FindByTitle 


Input: a target string and a list of CDs Output: Prints all CDs in the list of CDs that have the title target.
Description: Program should print all elements in the list of CDs that have a title that matches target. Function 

FindByGenre

Input: a target string and a list of CDs Output: Prints all CDs in the list of CDs that have the genre target.
Description: Program should print all elements in the list of CDs that have the genre given in target. Function 

FindByArtist 


Input: a target string and a list of CDs Output: Prints all CDs in the list of CDs that have target listed as the artist.
Description: Program should print all elements in the list of CDs that have the artist that matches target. Function 

FindByPrice

Input: the price (a decimal number) and a list of CDs Output: Prints all CDs in the list of CDs that cost at most the given price.
Description: Program finds all CDs that cost at most the amount specified by price.

Testing

Remember to test your program is working correctly. For example, you can print the list after it has been sorted to confirm that each sort function is working correctly. 


File:


CD_Store.txt 


Code :


class CD:


def __init__(self,aName,sName,type,price):
self.aName=aName
self.sName=sName
self.type=type
self.price=price

def getArtist(self):
return self.sName

def getPrice(self):
return str(self.price)

def __str__(self):
return ("{} by {} at {} is of {} Genre".format(self.aName,self.sName,self.getPrice(),self.type))
def __rep__(self):
return self.aName

class StoreHelper:


f=open("CD_Store.txt","r+")
listCD=[]

def __init__(self):
for f1 in self.f.readlines():
try:
price=float(f1.split(",")[3])
except Exception as e:
pass

self.listCD.append(CD(f1.split(",")[0],f1.split(",")[1],f1.split(",")[2],price))
def sortByArtist(self):

sortedList=sorted(self.listCD, key=lambda x: x.sName)

newFile=open("CD_Store.txt","w+")

for cd in sortedList:
print(cd,"\n")
newFile.write(cd.aName+","+cd.sName+","+cd.type+","+str(cd.price)+"\n")


def sortByPrice(self):
sortedList=sorted(self.listCD, key=lambda x: x.price)


newFile=open("CD_Store.txt","w+")

for cd in sortedList:
print(cd,"\n")
newFile.write(cd.aName+","+cd.sName+","+cd.type+","+cd.getPrice()+"\n")

def searchTitle(self,target):
for cd in self.listCD:

if(target.lower() in cd.aName.lower()):
print(cd)

def searchGenre(self,target):
for cd in self.listCD:
if(target.lower() in cd.type.lower()):
print(cd)

def searchArtist(self,target):
for cd in self.listCD:
if(target.lower() in cd.sName.lower()):
print(cd)

def searchPrice(self,targetPrice):
for cd in self.listCD:
if(cd.price<=targetPrice):
print(cd)


def main():
storeHelper=StoreHelper()

while(True):
print("\nPlease Choose from below \n" )

print("1 to Sort by Artist")

print("2 for Sort by Price")

print("3 for FindByTitle")

print("4 for FindByGenre")

print("5 for FindByArtist")

print("6 for FindByPrice\n")

print('quit to quit\n')

i=input()

if(i=='1'):
storeHelper.sortByArtist()
elif (i=='2'):
storeHelper.sortByPrice()
elif (i=='3'):
storeHelper.searchTitle(input("Enter Taget Title here : "))
elif (i=='4'):
storeHelper.searchGenre(input("Enter Taget Genre here : "))
elif (i=='5'):
storeHelper.searchArtist(input("Enter Artist name here : "))
elif (i=='6'):
storeHelper.searchPrice(float(input("Enter Target price here : ")))
elif (i.lower()=='quit'):
break

main()
  

For any query please comment down below.....



 
 

 





Friday, September 21, 2018

Patient Management System Python Console Based

ScreenShots:










Github link : https://github.com/mrdishant/Python/blob/master/patientManagement.py

Code:


class Patient:


def __init__(self,):
self.name=None
self.age=None
self.gender=None


def showDetails(self):
print("=Patient Details=")
print("Name : ",self.name)
print("Age : ",self.age)
print("Gender : ",self.gender)


class PMSystem:

patients=list()

def addPatient(self):
p1=Patient()

p1.name=input("Enter Patients Name : ")

p1.age=int(input("Enter Age : "))

p1.gender=int(input("Specify Gender 0 for Male 1 for Female : "))

self.patients.append(p1)

print("!!! Patient Added Successfully !!!\n")

def showAll(self):

for patient in self.patients:
print("================")
patient.showDetails()

print("================\n")


def showAllAgeSort(self):

sortedList=sorted(self.patients, key=lambda x: x.age)
for patient in sortedList:

print("================")
patient.showDetails()
print("================\n")

def showAllGender(self,value):

for Patient in self.patients:
if(Patient.gender==value):

print("================")
Patient.showDetails()

print("================\n")

def main():

pmsystem=PMSystem()

while(True):
print("\nPlease Choose from below \n" )

print("1 to Add Patient")

print("2 for List of Patients")

print("3 for List of Patients (Age Sort)")

print("4 for List of Patients (Male)")

print("5 for List of Patients (Female)\n")

i=input();

if(i=='1'):
pmsystem.addPatient()
elif (i=='2'):
pmsystem.showAll()
elif (i=='3'):
pmsystem.showAllAgeSort()
elif (i=='4'):
pmsystem.showAllGender(0)
elif (i=='5'):
pmsystem.showAllGender(1)


main()

Thursday, June 7, 2018

incoChat

incoChat Legal Info



Acceptable use of our services

Our Terms and Policies. You must use our Services according to our Terms and posted policies. If we disable your account for a violation of our Terms, you will not create another account without our permission.

Legal and Acceptable Use. You must access and use our Services only for legal, authorized, and acceptable purposes. You will not use (or assist others in using) our Services in ways that: (a) violate, misappropriate, or infringe the rights of incoChat, our users, or others, including privacy, publicity, intellectual property, or other proprietary rights; (b) are illegal, obscene, defamatory, threatening, intimidating, harassing, hateful, racially, or ethnically offensive, or instigate or encourage conduct that would be illegal, or otherwise inappropriate, including promoting violent crimes; (c) involve publishing falsehoods, misrepresentations, or misleading statements; (d) impersonate someone; (e) involve sending illegal or impermissible communications such as bulk messaging, auto-messaging, auto-dialing, and the like; or (f) involve any non-personal use of our Services unless otherwise authorized by us.

Harm to incoChat or Our Users. You must not (or assist others to) access, use, copy, adapt, modify, prepare derivative works based upon, distribute, license, sublicense, transfer, display, perform, or otherwise exploit our Services in impermissible or unauthorized manners, or in ways that burden, impair, or harm us, our Services, systems, our users, or others, including that you must not directly or through automated means: (a) reverse engineer, alter, modify, create derivative works from, decompile, or extract code from our Services; (b) send, store, or transmit viruses or other harmful computer code through or onto our Services; (c) gain or attempt to gain unauthorized access to our Services or systems; (d) interfere with or disrupt the integrity or performance of our Services; (e) create accounts for our Services through unauthorized or automated means; (f) collect the information of or about our users in any impermissible or unauthorized manner; (g) sell, resell, rent, or charge for our Services; or (h) distribute or make our Services available over a network where they could be used by multiple devices at the same time.

Keeping Your Account Secure. You are responsible for keeping your device and your incoChat account safe and secure, and you must notify us promptly of any unauthorized use or security breach of your account or our Services.
Third-party services

Our Services may allow you to access, use, or interact with third-party websites, apps, content, and other products and services. For example, you may choose to use third-party data backup services (such as iCloud or Google Drive) that are integrated with our Services or interact with a share button on a third party’s website that enables you to send information to your incoChat contacts. Please note that when you use third-party services, their own terms and privacy policies will govern your use of those services.
Licenses

Your Rights. incoChat does not claim ownership of the information that you submit for your incoChat account or through our Services. You must have the necessary rights to such information that you submit for your incoChat account or through our Services and the right to grant the rights and licenses in our Terms.

incoChat’s Rights. We own all copyrights, trademarks, domains, logos, trade dress, trade secrets, patents, and other intellectual property rights associated with our Services. You may not use our copyrights, trademarks, domains, logos, trade dress, patents, and other intellectual property rights unless you have our express permission and except in accordance with our Brand Guidelines. You may use the trademarks www.facebookbrand.com/trademarks of our affiliated companies only with their permission, including as authorized in any published brand guidelines.

Your License to incoChat. In order to operate and provide our Services, you grant incoChat a worldwide, non-exclusive, royalty-free, sublicensable, and transferable license to use, reproduce, distribute, create derivative works of, display, and perform the information (including the content) that you upload, submit, store, send, or receive on or through our Services. The rights you grant in this license are for the limited purpose of operating and providing our Services (such as to allow us to display your profile picture and status message, transmit your messages, store your undelivered messages on our servers for up to 30 days as we try to deliver them, and otherwise as described in our Privacy Policy).

incoChat’s License to You. We grant you a limited, revocable, non-exclusive, non-sublicensable, and non-transferable license to use our Services, subject to and in accordance with our Terms. This license is for the sole purpose of enabling you to use our Services, in the manner permitted by our Terms. No licenses or rights are granted to you by implication or otherwise, except for the licenses and rights expressly granted to you.
Reporting third-party copyright, trademark, and other intellectual property infringement

To report claims of third-party copyright, trademark, or other intellectual property infringement, please visit our Intellectual Property Policy. We may terminate your incoChat account if you repeatedly infringe the intellectual property rights of others.
Disclaimers

YOU USE OUR SERVICES AT YOUR OWN RISK AND SUBJECT TO THE FOLLOWING DISCLAIMERS. WE ARE PROVIDING OUR SERVICES ON AN “AS IS” BASIS WITHOUT ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, TITLE, NON-INFRINGEMENT, AND FREEDOM FROM COMPUTER VIRUS OR OTHER HARMFUL CODE. WE DO NOT WARRANT THAT ANY INFORMATION PROVIDED BY US IS ACCURATE, COMPLETE, OR USEFUL, THAT OUR SERVICES WILL BE OPERATIONAL, ERROR FREE, SECURE, OR SAFE, OR THAT OUR SERVICES WILL FUNCTION WITHOUT DISRUPTIONS, DELAYS, OR IMPERFECTIONS. WE DO NOT CONTROL, AND ARE NOT RESPONSIBLE FOR, CONTROLLING HOW OR WHEN OUR USERS USE OUR SERVICES OR THE FEATURES, SERVICES, AND INTERFACES OUR SERVICES PROVIDE. WE ARE NOT RESPONSIBLE FOR AND ARE NOT OBLIGATED TO CONTROL THE ACTIONS OR INFORMATION (INCLUDING CONTENT) OF OUR USERS OR OTHER THIRD PARTIES. YOU RELEASE US, OUR SUBSIDIARIES, AFFILIATES, AND OUR AND THEIR DIRECTORS, OFFICERS, EMPLOYEES, PARTNERS, AND AGENTS (TOGETHER, THE “incoChat PARTIES”) FROM ANY CLAIM, COMPLAINT, CAUSE OF ACTION, CONTROVERSY, OR DISPUTE (TOGETHER, “CLAIM”) AND DAMAGES, KNOWN AND UNKNOWN, RELATING TO, ARISING OUT OF, OR IN ANY WAY CONNECTED WITH ANY SUCH CLAIM YOU HAVE AGAINST ANY THIRD PARTIES. YOU WAIVE ANY RIGHTS YOU MAY HAVE UNDER CALIFORNIA CIVIL CODE §1542, OR ANY OTHER SIMILAR APPLICABLE STATUTE OR LAW OF ANY OTHER JURISDICTION, WHICH SAYS THAT: A GENERAL RELEASE DOES NOT EXTEND TO CLAIMS WHICH THE CREDITOR DOES NOT KNOW OR SUSPECT TO EXIST IN HIS OR HER FAVOR AT THE TIME OF EXECUTING THE RELEASE, WHICH IF KNOWN BY HIM OR HER MUST HAVE MATERIALLY AFFECTED HIS OR HER SETTLEMENT WITH THE DEBTOR.
Limitation of liability

THE incoChat PARTIES WILL NOT BE LIABLE TO YOU FOR ANY LOST PROFITS OR CONSEQUENTIAL, SPECIAL, PUNITIVE, INDIRECT, OR INCIDENTAL DAMAGES RELATING TO, ARISING OUT OF, OR IN ANY WAY IN CONNECTION WITH OUR TERMS, US, OR OUR SERVICES, EVEN IF THE incoChat PARTIES HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. OUR AGGREGATE LIABILITY RELATING TO, ARISING OUT OF, OR IN ANY WAY IN CONNECTION WITH OUR TERMS, US, OR OUR SERVICES WILL NOT EXCEED THE GREATER OF ONE HUNDRED DOLLARS ($100) OR THE AMOUNT YOU HAVE PAID US IN THE PAST TWELVE MONTHS. THE FOREGOING DISCLAIMER OF CERTAIN DAMAGES AND LIMITATION OF LIABILITY WILL APPLY TO THE MAXIMUM EXTENT PERMITTED BY APPLICABLE LAW. THE LAWS OF SOME STATES OR JURISDICTIONS MAY NOT ALLOW THE EXCLUSION OR LIMITATION OF CERTAIN DAMAGES, SO SOME OR ALL OF THE EXCLUSIONS AND LIMITATIONS SET FORTH ABOVE MAY NOT APPLY TO YOU. NOTWITHSTANDING ANYTHING TO THE CONTRARY IN OUR TERMS, IN SUCH CASES, THE LIABILITY OF THE incoChat PARTIES WILL BE LIMITED TO THE FULLEST EXTENT PERMITTED BY APPLICABLE LAW.
Indemnification

You agree to defend, indemnify, and hold harmless the incoChat Parties from and against all liabilities, damages, losses, and expenses of any kind (including reasonable legal fees and costs) relating to, arising out of, or in any way in connection with any of the following: (a) your access to or use of our Services, including information provided in connection therewith; (b) your breach or alleged breach of our Terms; or (c) any misrepresentation made by you. You will cooperate as fully as required by us in the defense or settlement of any Claim.
Dispute resolution

Forum and Venue. If you are a incoChat user located in the United States or Canada, the “Special Arbitration Provision for United States or Canada Users” section below applies to you. Please also read that section carefully and completely. If you are not subject to the “Special Arbitration Provision for United States or Canada Users” section below, you agree that you will resolve any Claim you have with us relating to, arising out of, or in any way in connection with our Terms, us, or our Services (each, a “Dispute,” and together, “Disputes”) exclusively in the United States District Court for the Northern District of California or a state court located in San Mateo County in California, and you agree to submit to the personal jurisdiction of such courts for the purpose of litigating all such Disputes.

Governing Law. The laws of the State of California govern our Terms, as well as any Disputes, whether in court or arbitration, which might arise between incoChat and you, without regard to conflict of law provisions.

Tuesday, April 24, 2018

Tic Tac Toe Python

Program :Write a Program For tic tac toe game for 0 and X.

Code :

Link:   https://inventwithpython.com/chapter10.html

Output:




Next Animated Banner Program