Simple word counter program in python - python

I have tried to create a really simple program that counts the words that you have written. When I run my code, I do not get any errors, the problem is that it always says: "the numbers of words are 0" when it is clearly not 0. I have tried to add this and see if it actually reads anything from the file: print(data) . It doesn't print anything ): so there must be a problem with the read part.
print("copy ur text down below")
words = input("")
f = open("data.txt", "w+")
z = open("data.txt", "r+")
info = f.write(words)
data = z.read()
res = len(data.split())
print("the numbers of words are " + str(res))
f.close()
Thx in advance

This is beacuse you haven't closed the file after writing to it. Use f.close() before using z.read()
Code:
print("copy ur text down below")
words = input("")
f = open("data.txt", "w+")
z = open("data.txt", "r+")
info = f.write(words)
f.close() # closing the file here after writing
data = z.read()
res = len(data.split())
print("the numbers of words are " + str(res))
f.close()
Output:
copy ur text down below
hello world
the numbers of words are 2

After writing to f with f.write, you should close f with f.close before calling z.read. See here.

Related

Removing characters in a file and also making it neat

I want to basically remove all the characters in delete list from the file (Line 11 to 15). What would be the neatest way to delete the words without making the code not neat. I am not sure whether to open the file again here which I know would not be the right way but I can't think of a different solution. Any help would be appreciated.
from os import write
import re
def readText():
with open(r'C:\Users\maxth\Desktop\TextCounter\Text.txt') as f:
print(f.read())
def longestWord():
with open(r'C:\Users\maxth\Desktop\TextCounter\Text.txt', 'r+') as f:
users_text = f.read()
#I want to basically remove all the char in delete list from the file. What would be the neatest way to delete the words without making the code not neat. I am not sure wether to open the file again here and re write it or what!
deleteList = ['!','£','$','%','^','&','*','()','_','+']
for line in f:
for word in deleteList:
line = line.replace(word, '')
longest = max(users_text.split(), key=len)
count_longest = str(len(longest))
print('The longest word in the file is: ' + long)
print('Thats a total of '+count_longest+' letters!')
def writeWord():
with open(r'C:\Users\maxth\Desktop\TextCounter\Text.txt', 'w') as f:
users_text = input('Enter your desired text to continue. \n: ')
f.write(users_text)
f.close()
with open(r'C:\Users\maxth\Desktop\TextCounter\Text.txt', 'r') as file:
print(file.read())
longestWord()
Had to re work it and implement it in a different def. Need to add relative paths and will be alot cleaner aswell.
from os import write
import re
def longestWord():
with open(r'C:\Users\maxth\Desktop\TextCounter\Text.txt', 'r+') as f:
users_text = f.read()
longest = max(users_text.split(), key=len)
count_longest = str(len(longest))
print('The longest word in the file is: ' + longest)
print('Thats a total of '+count_longest+' letters!')
def writeWord():
with open(r'C:\Users\maxth\Desktop\TextCounter\Text.txt', 'w') as f:
users_text = input('Enter your desired text to continue. \n: ')
cleanText = re.sub('[^a-zA-Z0-9 \n\.]', ' ', users_text)
f.write(cleanText)
with open(r'C:\Users\maxth\Desktop\TextCounter\Text.txt', 'r') as clean:
print('\nRemoved any illegal characters. Here is your text:\n\n' + cleanText + '\n')
f.close()
while True:
print("""
Welcome to Skies word text counter!
====================================================
""")
writeWord()
longestWord()
userDecide = input("""
====================================================
Would you like to enter new text and repeat?
Type 'yes' to continue else program will terminate.
====================================================
: """)
if not userDecide.lower == 'yes':
print('Application closing...')
exit()

How to add numbers to a file

I'm a beginner at Python and I just learned about opening files, reading files, writing files, and appending files.
I would I like to implement this to a little project that I'm making that asks for the user's name and appends it to a txt file named "HallOfFame.txt"
try:
infile = open('HallOfFame.txt', 'r')
file_contents = infile.read()
print(file_contents)
infile.close()
except:
FileNotFoundError
print("No Human Has Ever Beat Me... mwah-ha-ha-ha!")
name_file = open("HallOfFame.txt", 'a')
name_record = input("Please enter your name: ")
name_file.write(str(name_record) + '\n')
name_file.close()
Everytime someone adds their name, I'd like it to become something like this:
Vix
Mike
Valerie
Something similar like that (above) where they have to run the program again to see the Hall of Fame.
Thank you!
I can understand your question. you can try using the JSON module and do something like this.
import json
list = [1, "Vix"]
with open ('HallOfFame.txt', 'w') as filehandle:
json.dump(list, filehandle)
here you can update the list every time you get input. and write it to the text file. but the appearance will look like this.
[1, "Vix"]
[2, "Mike"]
[3, "Valerie"]
count = 0
try:
infile = open('HallOfFame.txt', 'r')
file_contents = infile.readlines()
if len(file_contents) != 0:
print("\nHall of Fame")
for line in file_contents:
count += 1
print("{}. {}".format(count, line.strip()))
print()
infile.close()
except:
FileNotFoundError
print("No Human Has Ever Beat Me... mwah-ha-ha-ha!")
name_file = open("HallOfFame.txt", 'a')
name_record = input("Please enter your name: ")
name_file.write(str(name_record) + "\n")
name_file.close()

Error being written to file when trying to write output

In this spellchecking program i created i seem to be getting a error when trying to write to the output file.The file is created but instead of the output being written an error " <_io.TextIOWrapper name='f.txt' mode='w' encoding='cp1252'>name " is.
I've tried looking for solutions.
print('Spell checking program for Exam 3 lab')
inputFile = input('Enter the name of the file to input from: ')
outputFile = input('Enter the name of the file to output to: ')
f = open("linuxwords.txt", "r")
sent = open(inputFile+ '.txt', "r")
butt = open(outputFile+'.txt', 'w')
word = sent.readline()
print ("mispelled words are:")
while word:
word = word.lower()
success = False
x = word.split()
y=len(x)
for i in x:
success = False
f = open("linuxwords.txt", "r")
line = f.readline()
while line:
if i == line.strip():
success = True
break
line = f.readline()
f.close()
if success == False:
print (i)
word = sent.readline()
with open(outputFile+'.txt', 'w') as f:
f.write(str(butt))
f.write(i)
try:
'''''''
I'm sure my mistake is here, idk
'''''''
f = open(outputFile, "w")
f.write(i)
except:
print('The file',outputFile, 'did not open.')
sent.close()
''''''
Result below
''''''''
Spell checking program for Exam 3 lab
Enter the name of the file to input from: spw
Enter the name of the file to output to: f
misspelled words are:
deks
chris
delatorre
huis
lst
f = open(outputFile)
f.write(i)
You're opening the file for reading, and then trying to write to it.

Find a dot in a text file and add a newline to the file in Python?

I read from a file, if it finds a ".", it should add a newline "\n" to the text and write it back to the file. I tried this code but still have the problem.
inp = open('rawCorpus.txt', 'r')
out = open("testFile.text", "w")
for line in iter(inp):
l = line.split()
if l.endswith(".")
out.write("\n")
s = '\n'.join(l)
print(s)
out.write(str(s))
inp.close()
out.close()
Try This ( Normal way ):
with open("rawCorpus.txt", 'r') as read_file:
raw_data = read_file.readlines()
my_save_data = open("testFile.text", "a")
for lines in raw_data:
if "." in lines:
re_lines = lines.replace(".", ".\r\n")
my_save_data.write(re_lines)
else:
my_save_data.write(lines + "\n")
my_save_data.close()
if your text file is not big you can try this too :
with open("rawCorpus.txt", 'r') as read_file:
raw_data = read_file.read()
re_data = raw_data.replace(".", ".\n")
with open("testFile.text", "w") as save_data:
save_data.write(re_data)
UPDATE ( output new lines depends on your text viewer too! because in some text editors "\n" is a new line but in some others "\r\n" is a new line. ) :
input sample :
This is a book. i love it.
This is a apple. i love it.
This is a laptop. i love it.
This is a pen. i love it.
This is a mobile. i love it.
Code:
last_buffer = []
read_lines = [line.rstrip('\n') for line in open('input.txt')]
my_save_data = open("output.txt", "a")
for lines in read_lines:
re_make_lines = lines.split(".")
for items in re_make_lines:
if items.replace(" ", "") == "":
pass
else:
result = items.strip() + ".\r\n"
my_save_data.write(result)
my_save_data.close()
Ouput Will Be :
This is a book.
i love it.
This is a apple.
i love it.
This is a laptop.
i love it.
This is a pen.
i love it.
This is a mobile.
i love it.
You are overwriting the string s in every loop with s = '\n'.join(l).
Allocate s = '' as empty string before the for-loop and add the new lines during every loop, e.g. with s += '\n'.join(l) (short version of s = s + '\n'.join(l)
This should work:
inp = open('rawCorpus.txt', 'r')
out = open('testFile.text', 'w')
s = '' # empty string
for line in iter(inp):
l = line.split('.')
s += '\n'.join(l) # add new lines to s
print(s)
out.write(str(s))
inp.close()
out.close()
Here is my own solution, but still I want one more newline after ".", that this solution not did this
read_lines = [line.rstrip('\n') for line in open('rawCorpus.txt')]
words = []
my_save_data = open("my_saved_data.txt", "w")
for lines in read_lines:
words.append(lines)
for word in words:
w = word.rstrip().replace('.', '\n.')
w = w.split()
my_save_data.write(str("\n".join(w)))
print("\n".join(w))
my_save_data.close()

Explaining how to convert a list of numbers back into words to make up the original array

import re
sentence=input('enter sentence')
punctuation=(re.findall(r"[\w'\"]+|[.,!?;:_-]", sentence))
print(punctuation)`enter code here`
positions = [punctuation.index(x) for x in punctuation]
print(positions)
test1=(", ".join(str(i) for i in positions))
words=" ".join(sorted(set(punctuation), key=punctuation.index))
print(words)
with open('1.txt', 'w') as f:#this creates the name of the file called task 2 which will contain my data ad allows the computer to locate the fle and add in the data. The 'w' makes the file writable so i can add in my data, without it displaying an error, using f as a variable.
f.write(str(words))
with open('2.txt', 'w') as f:
f.write(str(test1))
f.close()
openfile=input('what is your file name for the compressed sentence?')
openfile = open(openfile, "r")
print ( openfile.read())
openfile=input('what is your file name for the compressed positions?')
openfile = open(openfile, "r")
print ( openfile.read())
#This is for turning positions back into numbers
openfile = open('1.txt', "r")
test=openfile.read()
#print(test)
blankarray=[]
for i in test.split(" "):
blankarray.append(i)
#print(blankarray)
openfile.close
openfile = open('2.txt', "r")
test=openfile.read()
#print(test)
blankarray2=[]
for i in test.split(","):
blankarray2.append(int(i))
print(blankarray2)
openfile.close
blankstring=""
for i in range(len(blankarray2)):
#print(i)
blankstring=blankstring+blankarray[blankarray2[i]] + " "
print(blankstring)
The second part of code converts a list of numbers back into words to make up the array. However i dont really understand how it works. Any help would be useful

Categories

Resources