In: Computer Science
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)
If you have any doubts, please give me comment...
pos_file = open("Positive.txt", 'r')
#positive words are now in a list
# striping newlines and carriage returns
pos_list = [line.strip() for line in pos_file.readlines()]
pos_file.close()
p_file = open("Practice_forhw1.txt", 'r')
# striping newlines and carriage returns
p_list = [line.strip() for line in p_file.readlines()]
p_file.close()
for word in pos_list:
if word in p_list:
pos = p_list.index(word)
if pos!=-1:
p_list[pos] = "+1"
# restoring elements to file
fout = open("Practice_forhw1.txt", 'w')
print('\n'.join(p_list), file=fout)
fout.close()