Python Coding Question (Data Science)
Hello I am having difficulty writing a code in python to do a specific task. I have two text files, Positive.txt and Practice_forhw1.txt. I want to write a script that will check if any words in Practice_forhw1.txt match any of the words in Positive.txt then the word would get replaced with a "+1" in the Practice_forhw1.txt and then print out the Practice_forhw1.txt. (i.e if the word "happy" is in both Positive.txt and Practice_forhw1.txt then I want the word "happy" to get replaced with a +1 in the Practice_forhw1.txt file.
My poor attempt below:
pos_file = open("Positive.txt", 'r')
#positive words are now in a list
pos_list = pos_file.readlines()
p_file = open("Practice_forhw1.txt", 'r')
p_list = p_file.readlines()
for word in p_list:
if word in p_list == word in pos_list:
word = word.replace(word, '+1')
print (word)
In: Computer Science
C++
Add a function that finds & displays all the words that begin with the letter 's'.
The text file "dickens.txt" is as follows:
It was the best of times, it was the worst of times, it was the age of wisdom, it was the age of foolishness, it was the epoch of belief, it was the epoch of incredulity, it was the season of Light, it was the season of Darkness, it was the spring of hope, it was the winter of despair...
Display this at the end of the program which should look like this:
WORDS THAT BEGIN WITH 'S': season, spring
"spring" appears twice, duplicate works should only appear once.
The code is as follows:
#include <iostream>
#include <fstream>
#include <string>
#include <set>
using namespace std;
multiset<string> display_and_load_words(string
filename);
set<string> get_unique_words(multiset<string>&
words);
int main() {
cout << "The Word Counter program\n\n";
string filename = "dickens.txt";
cout << "FILE TEXT: ";
auto words = display_and_load_words(filename);
cout << "WORD COUNT: " << words.size()
<< endl << endl;
auto unique_words = get_unique_words(words);
cout << unique_words.size() << " UNIQUE WORDS:
";
for (string word : unique_words) {
cout << word << '
';
}
cout << endl << endl;
cout << "COUNT PER WORD: ";
for (string word : unique_words) {
cout << word << '='
<< words.count(word) << ' ';
}
cout << endl << endl;
}
multiset<string> display_and_load_words(string filename)
{
multiset<string> words;
ifstream infile(filename);
if (infile) {
string word;
while (infile >> word) {
cout <<
word << ' ';
string new_word = "";
for (char c : word) {
if (c == '.' || c == ',') {
continue;
}
else if (isupper(c)) {
new_word += tolower(c);
}
else {
new_word += c;
}
}
words.insert(new_word);
}
cout << endl <<
endl;
infile.close();
}
return words;
}
set<string> get_unique_words(multiset<string>&
words) {
set<string> unique_words;
for (string word : words) {
auto search =
unique_words.find(word);
if (search == unique_words.end())
{
unique_words.insert(word);
}
}
return unique_words;
}
In: Computer Science
Suppose that you are given a set of words; and two words from the set: word 1 and word 2.
Write a program which will transform word 1 into word 2 by changing a single letter in word 1 at a time.
Every transition that word 1 takes will have to be in the set of words.
You must output the smallest sequence of transitions possible to convert word 1 into word 2.
You may assume that all the words in the dictionary are the same length.
The first line will be word 1 and word 2 separated by a comma, followed by the set of words. The set of words will be terminated by a ‘-1’.
Input:
DOG,GOD
DOG
BOG
GOG
ABH
GOD
THU
IOP
-1
Output:
DOG -> GOG -> GOD
I have a code that does this but its all done in a textfile, I need it to be all on the console(using cin,cout and not the fstream)
#include
#include
#include
#include
#include
#include
#include
using namespace std;
class WordLadder {
private:
list dict; //list of possible words in ladder
void printstack(stack stack, ofstream &outfile);
bool wordcompare(string word, string dictword);
public:
WordLadder(const string &file);
void outputLadder(const string &start, const string &end,
const string &outputFile);
};
WordLadder::WordLadder(const string &file) {
string word;
ifstream infile;
infile.open(file.c_str());
if (infile.is_open()) {
while (!infile.eof()) {
getline(infile,word);
if (word.size() != 5) {
cout << "Warning: Word longer than 5 characters detected in
dictionary." << endl;
}
dict.push_back(word.c_str());
}
infile.close();
return;
} else {
cout << "Error opening input file." << endl;
return;
}
}
void WordLadder::outputLadder(const string &start, const string
&end, const string &outputFile) {
cout << "Finding
word ladder from " << start << " to " << end
<< ": ";
ofstream outfile;
outfile.open(outputFile.c_str());
if (!outfile.is_open()) {
cout << "Opening output file failed." << endl;
return;
}
// set up the stuff
queue< stack > queue;
stack< string > stack;
string word;
list::iterator it;
bool startgood = false, endgood = false;
// initial validity
tests
for (it=dict.begin();it!=dict.end();++it) {
if (*it == start) {
startgood = true;
}
if (*it == end) {
endgood = true;
}
}
if (!startgood || !endgood) {
cout << "Starting or ending word was not found in the
dictionary." << endl;
return;
}
if (start == end) {
outfile << start;
return;
}
stack.push(start);
queue.push(stack);
// find the first
word, delete it
dict.remove(start);
while(!queue.empty()) {
// get the word off of the top of the front stack
word = queue.front().top();
for (it=dict.begin();it!=dict.end();++it) {
// wordcompare will decide if the word is off by one from the
dictionary word.
if (wordcompare(word,*it)) {
if (*it == end) {
// if the off by one word is the last word
// the ladder contains the entire stack -- output and return.
queue.front().push(end);
//print the stack
printstack(queue.front(),outfile);
//cout << "Operations: " << opers << endl
<< endl;
return;
}
// otherwise, create a copy of the front stack and push the
// off by one word from dictionary
stack = queue.front();
stack.push(*it);
queue.push(stack);
it = dict.erase(it);
// decrement iterator by one to correct for the advanced
iterator
// returned by the std::list::erase function
it--;
}
}
queue.pop();
}
// if a word ladder is not found, then do this
if (outfile.is_open()) {
outfile << "No Word Ladder Found!!";
cout << "No Word Ladder Found!!";
}
}
bool WordLadder::wordcompare(string word, string dictword) {
int hits = 0;
for (int i=0; i<5; i++) {
if (word[i] == dictword[i]) { hits++; }
}
if (hits == 4) {
return true;
} else {
return false;
}
}
void WordLadder::printstack(stack stack, ofstream &outfile) {
int i = 0;
vector ladder;
while (!stack.empty()) {
ladder.push_back(stack.top());
stack.pop();
i++;
}
if (outfile.is_open())
{
while (i!=0) {
i--;
outfile << ladder.at(i);
cout << ladder.at(i);
if (i!=0) {
outfile << " ";
cout << " ";
}
}
cout << endl;
}
}
int main() {
string dictFile, wordBegin, wordEnd, outFile;
cout << "Enter the name of the dictionary file: ";
cin >> dictFile;
cout << endl;
cout << "Enter the name of the output file: ";
cin >> outFile;
cout << endl;
cout << "Enter the first word: ";
cin >> wordBegin;
cout << endl;
while (wordBegin.size() != 5) {
cout << "Word must have exactly 5 characters." <<
endl
<< "Please reenter the first word: ";
cin >> wordBegin;
cout << endl;
}
cout << "Enter the last word: ";
cin >> wordEnd;
cout << endl;
while (wordEnd.size() != 5) {
cout << "Word must have exactly 5 characters." <<
endl
<< "Please reenter the last word: ";
cin >> wordEnd;
cout << endl;
}
WordLadder wl(dictFile);
wl.outputLadder(wordBegin, wordEnd, outFile);
return 0;
}
In: Computer Science
I need convert this java code to C language. There is no string can be used in C. Thank you!
import java.util.Scanner;
public class Nthword
{
public static void main( String args[] )
{
String line;
int word;
Scanner stdin = new Scanner(System.in);
while ( stdin.hasNextLine() )
{
line = stdin.nextLine();
word = stdin.nextInt(); stdin.nextLine(); // get rid of the newline
after the int
System.out.println( "Read line: \"" + line + "\", extracting
word [" + word + "]" );
System.out.println( "Word #" + word + " is: " + extractWord( line,
word ) );
}
stdin.close();
System.out.println( "\nEnd of processing" );
}
// returns the first word of the string
private static String extractWord( String theLine, int word )
{
int start;
int end;
int spaces = 1;
String result = "";
// search for the nth non-blank character
for (start = 0; start < theLine.length() && spaces <
word; start++)
{
if ( Character.isSpaceChar( theLine.charAt( start ) ) )
{
spaces++;
}
}
// only need to continue if we haven't gone past the end of the
string
if ( start<theLine.length() )
{
// the next blank character is the end
for ( end=start ; end<theLine.length() &&
!Character.isSpaceChar( theLine.charAt( end ) ) ; end++ )
;
// we now have the word
result = theLine.substring( start, end );
}
return( result );
}
}
In: Computer Science
Write a program that will prompt for a word with at least five letters in it (if not, keep asking for input). Then evaluate the word to produce a count of all the vowels in the word. Sample output appears below.
Enter a word at least 5 characters
long:<SPC>cat<ENTER>
Enter a word at least 5 characters
long:<SPC>dog<ENTER>
Enter a word at least 5 characters
long:<SPC>concatenate<ENTER>
Letter Counts
=========
a: 2
e: 2
i: 0
o: 1
u: 0
In: Computer Science
Name: __________________________________________
Specifications:
public void reset()
Resets the WordMaker so that it is ready to start building a word.
public void addChar(newChar);
Adds a character to the WordMaker. If it is a letter and
WordMaker is making a word, it adds it to the end of the word. If
it is a letter and WordMaker is not making a word, it erases the
current word, and starts a new word with the letter. If it is not a
letter and WordMaker is making a word, it ends the word (unless
it is an apostrophe, treated specially as described above). If it is not
a letter and WordMaker is not making a word, it is ignored.
public boolean wordReady()
Returns true if the WordMaker has finished constructing a word,
false otherwise. After a reset, or when the WordMaker is first
constructed, it returns false. When a word has just been completed
(i.e., the first non-letter character has been added), it returns true.
Otherwise it returns false.
public String getWord()
Returns the word that the WordMaker has created when
WordReady returns true. It should not be called when WordReady
returns false.
In: Computer Science
def main():
# keeping asking user for a word or
name until user enters 0
while True:
word =
input('Enter a word/name to convert (enter 0 to quit):
').upper()
if word ==
'0': break
print(convert_to_soundex(word))
Whenever i try to run the program it tells me unintend doesn't match any outer identation level !!!!
In: Computer Science
For our current programming assignment I need to create a CleanWord method that reads in one variable string at a time and returns a cleaned word without any non letters. The instructions given to us are listed below:
“Clean word” method:
This is to be implemented as a separate method, so it can be called for either a dictionary word or book word.
The function will remove any non-letters, except an apostrophe (‘) and numbers from the word.
All letters will changed to lower case.
It will then return the updated word. The word could now be blank. The calling method will need to deal with this correctly.
I would appreciate the help!
In: Computer Science
SAMPLE PROGRAM RUN #1
Enter a word: carrot
First half: car
Second half: rot
SAMPLE PROGRAM RUN #2
Enter a word: plant
First half: pl
Second half: ant
Complete your answer by typing code below
import java.util.Scanner;
public class WordHalves
{
public static void main(String[] args)
{
Scanner reader = new Scanner(System.in);
System.out.print("Enter a word: ");
String word = reader.nextLine();
}
}
In: Computer Science
For each of the following propositions the first word in your answer should be the word True or the word False followed by a brief explanation as to why the proposition is true or false.
assume that Frank and Athena can produce either chairs or tables. If Athena has a comparative advantage in producing chairs, then she would be able to sell chairs for a higher price than Frank.
In: Economics