I am trying to create a block of code that scans a .txt file (first book of LOTR) and tallys the frequency of each letter into a dictionary. (say for instance if theres 500 3 letter words appearing in the book, the output will be displayed as 3:500, and so on).
I seemed to have gotten the code right as I have tried it on test documents before adding the dict() function, and it works by printing each word as a string in a list, though when I go to run it now, it prints the first word then outputs file not found (which is what ive coded for an exception), even though the file is present in my jupyter notebook.
Is there any way to fix this? what is the default directory that jupyter scans for?
All of your help is appreciated!
Code:
fname= input('Enter file: ')
#if len(fname) < 1: fname = 'LOTR.txt'
try:
fhand = open(fname)
d = dict()
for line in fhand:
words = line.split()
print(words)
for word in words:
d1[word] = d1.get(word, 0) + 1
print (d1)
except:
print("File not found")
output:
Enter file: LOTR.txt
['PROLOGUE']
File not found
Your problem is that you are accessing d1 before defining it.
Also you should catch specific exceptions instead of using a bare except. The following should solve your problem:
fname= input('Enter file: ')
#if len(fname) < 1: fname = 'LOTR.txt'
try:
fhand = open(fname)
d = dict()
for line in fhand:
words = line.split()
print(words)
for word in words:
d[word] = d.get(word, 0) + 1
print(d)
except FileNotFoundError:
print("File not found")
except Exception as e:
print("Other error occurred", e)
Related
photo
This code can't load the log.txt file.
The file is in the temp folder.
Why can't I load it?
This code only displays the text: Search word: ABC.
text = input("Search word: ABC")
with open("C:\Temp\log.txt", encoding = "utf-8") as f:
cnt = 0
for line in f:
l = line.strip().split()
if (l[-1] == text):
print(line.strip())
cnt += 1
if (cnt): print(cnt, "count")
else: print(text, "No data.")
It seems like you need to type the word after running the program. The "ABC" you see is the prompt from the script i.e. it is not entered by you. That's why the program keeps running, waiting for the input and doesn't go further.
Here's your code slightly modified to make it clear.
text = input("Search word: ")
with open("C:\Temp\log.txt", encoding="utf-8") as f:
cnt = 0
for line in f:
if text in line:
print(line.strip())
cnt += 1
if cnt:
print(cnt, "count")
else:
print(text, "No data.")
I guess you understand that your code:
ask the user to input some text
count the occurrences of that text in the file C:\Temp\log.txt, under the conditions:
the text does not contains space
the text is at the end of the line
the text may be followed by one or more spaces
the text must be preceded by one or more spaces
the file cannot have empty lines
Under those conditions, your code should behave nicely. I would recommend to change text = input("Search word: ABC") to text = input("Search word: ") to make it clear that the user need to input some text.
If you still have unexpected results, check if you don't have any character encoding issue (like a terminal default encoding not being utf-8)
I'm trying to print "None" if the input entered by the user is not found in a text file I created. It should also print if the lines if word(s) are found in the text file.
My problem right now is that it is not doing both conditionals. If I were to remove the "line not in user_pass" it would not print anything. I just want the user to be able to know if the strings entered by the user can found in the file and will print that line or "none" if it is not found.
I commented out the ones where I tried fixing my code, but no use.
My code below:
def text_search(text):
try:
filename = "words.txt"
with open(filename) as search:
print('\nWord(s) found in file: ')
for line in search:
line = line.rstrip()
if 4 > len(line):
continue
if line.lower() in text.lower():
print("\n" + line)
# elif line not in text: # the function above will not work if this conditional commented out
# print("None")
# break
# if line not in text: # None will be printed so many times and line.lower in text.lower() conditional will not work
# print("none")
except OSError:
print("ERROR: Cannot open file.")
text_search("information")
I think you need to change for line in search: to for line in search.readlines(): I don't think you're ever reading from the file... Have you tried to just print(line) and ensure your program is reading anything at all?
#EDIT
Here is how I would approach the problem:
def text_search(text):
word_found = False
filename = "words.txt"
try:
with open(filename) as file:
file_by_line = file.readlines() # returns a list
except OSError:
print("ERROR: Cannot open file.")
print(file_by_line) # lets you know you read the data correctly
for line in file_by_line:
line = line.rstrip()
if 4 > len(line):
continue
if line.lower() in text.lower():
word_found = True
print("\n" + line)
if word_found is False:
print("Could not find that word in the file")
text_search("information")
I like this approach because
It is clear where you are reading the file and assigning it to a variable
This variable is then printed, which is useful for debugging
Less stuff is in a try: clause (I like to not hide my errors, but that's not a huge deal here because you did a good job specifying OSError however, what if an OSError occured during line = line.rstrip() for some reason...you would never know!!)
If this helped I'd appreciate if you would click that green check :)
Try this:-
def find_words_in_line(words,line):
for word in words:
if(word in line):
return True;
return False;
def text_search(text,case_insensitive=True):
words = list(map(lambda x:x.strip(),text.split()));
if(case_insensitive):
text = text.lower();
try:
filename = 'words.txt'
with open(filename) as search:
found = False;
for line in search:
line = line.strip();
if(find_words_in_line(words,line)):
print(line);
found = True;
if(not found):
print(None);
except:
print('File not found');
text_search('information');
Didn't really understand your code, so making one on my own according to your requirement.
I am beginner in programming and currently facing issue with simple task. I would need to print words, calculate number of particular words and also number of letters from txt.file. I would appreciate if someone could help me with this:
def main():
file_name = input("Input file. \n")
sum_of_letters = 0
number_words = 0
try:
words = open(file_name, "r")
print("File", file_name ,"includes the following words:")
for line in words:
line = line.rstrip()
words= line.split()
for i in words:
print(i)
sum_of_letters += len(i)
number_words += 1
print("---------------------------------------")
print("Number of words",number_words ,"ja", sum_of_letters, "kirjainta.")
close.words()
except OSError:
print("Error observed")
Your code is almost correct but you're using words to refer to both the file as well as the words in a single line. I've updated the code below to use different variables:
def main():
file_name = input("Input file. \n")
sum_of_letters = 0
number_words = 0
try:
words = open(file_name, "r")
print("File", file_name ,"includes the following words:")
for line in words:
line = line.rstrip()
words_in_line = line.split()
for i in words_in_line:
print(i)
sum_of_letters += len(i)
number_words += 1
print("---------------------------------------")
print("Number of words",number_words ,"ja", sum_of_letters, "kirjainta.")
words.close()
except OSError:
print("Error observed")
I'm a beginner in python & am having some problems with the structure of my homework assignment; my assignment is: "Write a program that asks the user for a filename, opens the file and reads through the file just once before reporting back to the user the number of characters (including spaces and end of line characters), the number of words, and the number of lines in the file.
If the user enters the name of a file that doesn't exist, your program should give her as many tries as she needs in order to type a valid filename. Obtaining a valid filename from the user is a common operation, so start by writing a separate, reusable function that repeatedly asks the user for a filename until she types in a file that your program is able to open."
And, I didn't start that way (& now I'm wondering if with the way I've structured it with "with/as", there's a way to even do that but my problem right now is getting it to go back into the try section of code after the error is thrown (I missed the class where this was explained so I've only ever read about this so I Know I'm not doing something right). I can get it to work as long as it's a filename that exists, if it's not, it prints nothing to the screen. Here's my code:
filename = input("please enter a file name to process:")
lineCount = 0
wordCount = 0
charCount = 0
try:
with open(filename, 'r') as file:
for line in file:
word = line.split()
lineCount = lineCount + 1
wordCount = wordCount + len(word)
charCount = charCount + len(line)
print("the number of lines in your file is:", lineCount)
print("the number of words in your file is", wordCount)
print("the number of characters in your file is:", charCount)
except OSError:
print("That file doesn't exist")
filename = input("please enter a file name to process:")
And, I'm not sure what I should do- if I should scrap this whole idea for a simple try: open(filename, 'r') / except: function of it=f there's anyway to salvage this.
So, I thought to fix it this way:
def inputAndRead():
"""prompts user for input, reads file & throws exception"""
filename = None
while (filename is None):
inputFilename = input("please enter a file name to process")
try:
filename = inputFilename
open(filename, 'r')
except OSError:
print("That file doesn't exist")
return filename
inputAndRead()
lineCount = 0
wordCount = 0
charCount = 0
with open(filename, 'r') as file:
for line in file:
word = line.split()
lineCount = lineCount + 1
wordCount = wordCount + len(word)
charCount = charCount + len(line)
print("the number of lines in your file is:", lineCount)
print("the number of words in your file is", wordCount)
print("the number of characters in your file is:", charCount)
But, I'm getting error: NameError: name 'file' is not defined
I would reorganize this code so that the file is opened in a loop. No matter how many times the user enters an invalid filename, the code will just ask for a new one and try again.
lineCount = 0
wordCount = 0
charCount = 0
f = None
while f is None:
filename = input("please enter a file name to process:")
try:
f = open(filename)
except OSError:
print("That file doesn't exist")
for line in file:
word = line.split()
lineCount = lineCount + 1
wordCount = wordCount + len(word)
charCount = charCount + len(line)
print("the number of lines in your file is:", lineCount)
print("the number of words in your file is", wordCount)
print("the number of characters in your file is:", charCount)
Write an infinite loop while True. When the file name is correct, at the end of the try, add a break.
Glad that helps
I am trying to create a simple word search program.
I have successfully opened an external file that contains the grid of the word search. I also have successfully opened a file that contains the words that are to be searched for. I have stored every line of the grid in a list and every word from the file in a list called words[].
I am attempting to search for the words in each line of the grid. My code currently does not search for the word in each line of the grid.
gridlines_horizontal = []
gridlines_vertical = []
words = []
not_found = []
found_words = {}
def puzzle(fname) :
print ""
for line in f :
gridlines_horizontal.append(line)
for line in gridlines_horizontal :
print line,
for item in zip(*(gridlines_horizontal[::-1])):
gridlines_vertical.append(item)
Here I am trying to get each word in words[] one at a time and see if the word is in any of the lines of the word search grid. If the word is present in any of the lines I am then trying to print the word. The code currently does not do this.
def horizontal_search(word,gridlines_horizontal) :
x = 0
for line in gridlines_horizontal :
if words[0] in line or words[0] in line[::-1]:
found_words.update({words[0]:" "})
print words[0]
else :
not_found.append(words)
x = x + 1
def vertical_search(word,gridlines_vertical):
x = 0
for line in gridlines_vertical:
if words[x] in line or words[x] in line[::-1]:
print words[0]
found_words.update({words[x]:" "})
else:
not_found.append(words[x])
x = x + 1
while True:
try:
fname = input("Enter a filename between double quotation marks: ")
with open(fname) as f:
puzzle(fname)
break
except IOError as e :
print""
print("Problem opening file...")
print ""
while True:
try:
fname2 = input("Enter a filename for your words between double quotation marks: ")
with open(fname2) as f:
for line in f:
words.append(line)
""" line in words:
line = lin """
break
except IOError as e :
print("")
print("Problem opening file...")
There are a couple mistakes in your code:
- You aren't being consistent in using words[x], in your code you would want to replace every words[0] with words[x] BUT
- this isn't necessary because you can use nested 'for' loops.
So for horizontal search:
def horizontal_search(words,gridlines_horizontal):
for word in words:
for line in gridlines_horizontal:
if word in line or word in line[::-1]:
found_words.update({word : " "})
print(word)
break
else:
not_found.append(word)
Did you look at find?
a = 'this is a string'
b = 'string'
if (a.find(b) > -1):
print 'found substring in string'
else:
print 'substring not found in string'
Live demo of above code
EDIT:
I am not sure if its a typo, but you are passing word as parameter instead of words
def horizontal_search(word,gridlines_horizontal) :
x = 0 ^----------------------------------
for line in gridlines_horizontal : |
if words[0] in line or words[0] in line[::-1]: |
^-- see here <------------not matching here -----
Similar issue with def vertical_search(words,gridlines_vertical) :