File Handling, Dictionary and Maps - python

So I was supposed to find the number of occurences of a text file, by following this kind of format.
But my code probably is entirely wrong.
text = open('text3.txt','r')
d = dict()
fname = input('Enter the file name:')
l = input('Enter letter to be searched:')
k = 0
with open(fname, 'r') as f:
for line in f:
words = line.split()
for i in words:
for letter in i:
if(letter == 1):
k = k+1
print('Occurences of the letter:')
print(k)
Can someone help me for this?

yeah you can iterate the characters instead:
fname = input('Enter the file name:')
char = input('Enter letter to be searched:')
i = 0
with open(fname, 'r') as f:
data = f.read()
for each in data:
if each == char:
i += 1
print(i)

Related

Dictionary python, don't write existing word

I want that if a word already exit in Dico.txt it doesn't write it again.
e = input("Mots: ")
f = e.split(" ")
with open("Dico.txt", "a") as f2:
for line in f:
for word in line.split():
f2.write(word + '\n')
You can use a list for this:
e = input("Mots: ")
f = e.split(" ")
u = []
with open("Dico.txt", "a") as f2:
for line in f:
for word in line.split():
if not word in u:
f2.write(word + '\n')
u.append(word)
else:
continue
#!/usr/bin/env python
f = open('Dico.txt', 'r')
f2 = open('new.txt', 'w')
w = input('The word? ')
for line in f:
for word in line.split():
l = line.replace(w, "")
f2.write(l.strip(" "))

Python incorrect indent for for-loop (Coursera Python Data Structure courses)

Why does my code print the empty list?
fname = input("Enter file name: ")
if len(fname) < 1 : fname = "mbox-short.txt"
fh = open(fname)
count = 0
lst = []
for line in fh:
line = line.rstrip()
word = line.split()
if len(word) < 0:
countinue
print(word[1])
the text file can be downloaded here
There are two issues that I found:
Be careful with the indent, which results the empty print
The space is matter to find the correct begging place, I accidentally missed the space so that produce the duplicated or repeated result.
#Assignment 8.5
#file name = mbox-short.txt
fname = input("Enter file name: ")
if len(fname) < 1 : fname = "mbox-short.txt"
fh = open(fname)
count = 0
for line in fh:
line = line.rstrip()
if not line.startswith('From '): #To check if the line staty with 'From '
continue #Note that there is a space behind the From, otherwise the print resuly would duplicated
word = line.split()
count = count + 1
print(word[1]) #be careful with the indent
print("There were", count, "lines in the file with From as the first word")

Counting number of words and letters from txt. file

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")

Reading and Printing multiple files into one outfile

When reading and printing through my files, printing through my cousole gives me the correct result, but writing to the outfile does not
with infile as f :
lines = f.readlines()
new_line = " "
for line in lines:
new_line = ''.join(line).replace('*',letter.upper())
new_line = new_line.replace(':',letter.lower())
print(new_line)
This prints out all of the letters that I inputted
with infile as f :
lines = f.readlines()
new_line = " "
for line in lines:
new_line = ''.join(line).replace('*',letter.upper())
new_line = new_line.replace(':',letter.lower())
outfile.write(new_line)
It only gives me the last letter of the word inputted.
folder = r"C:\Users\sarah\Documents\a CPS 111\Bonus PA\stars\stars"
# os.listdir(folder) returns a list of files in folder
file_list = os.listdir(folder)
letter_art = {}
word = str(input("Please input a letter: "))
word = word.upper()
for fname in file_list:
letter_extension_list = fname.split(".")
for letter in word:
key = letter
value = letter_extension_list[1]
value = "%s."%(key) + value
letter_art[key] = value
fname = "\\".join([folder, value])
infile = open(fname, "r")
outfile = open("word_art.txt", "w")
with infile as f :
lines = f.readlines()
new_line = " "
for line in lines:
new_line = ''.join(line).replace('*',letter.upper())
new_line = new_line.replace(':',letter.lower())
print(new_line)
outfile.write(new_line)
infile.close()
outfile.close()
This is the code I am currently working with. I am taking in symbols from a txt file and changing them to the coornading letter depending on what the user inputed
Open the output file before the loop instead of within it:
outfile = open("word_art.txt", "w")
for letter in word:
with open("test.txt",'r') as f :
lines = f.readlines()
with open('out.txt','w') as outfile:
for line in lines:
new_line = line.replace('*',letter.upper())
new_line = new_line.replace(':',letter.lower())
outfile.write(new_line)
This worked for me.
EDIT:
TigerhawkT3 is correct. I checked out your full code and you were opening the file again and again inside the loop, each time discarding the prior changes.

counting the lines and extract the floating point values and compute the average of the values

So i need to write a program that prompts for a file name, then opens that file and reads through the file, looking for lines of the form:X-DSPAM-Confidence: 0.8475
I am stuck in getting the sum of the extracted values and counting the lines and printing to show the user.
out_number = 'X-DSPAM-Confidence: 0.8475'
Num = 0.0
flag = 0
fileList = list()
fname = input('Enter the file name')
try:
fhand = open(fname)
except:
print('file cannot be opened:',fname)
for line in fhand:
fileList = line.split()
print(fileList)
for line in fileList:
if flag == 0:
pos = out_number.find(':')
Num = out_number[pos + 2:]
print (float(Num))
You have an example line in your code, and when you look through each line in your file, you compute the number in your example line, not in the line from the file.
So, here's what I would do:
import os
import sys
fname = input('Enter the file name: ')
if not os.path.isfile(fname):
print('file cannot be opened:', fname)
sys.exit(1)
prefix = 'X-DSPAM-Confidence: '
numbers = []
with open(fname) as infile:
for line in infile:
if not line.startswith(prefix): continue
num = float(line.split(":",1)[1])
print("found:", num)
numbers.append(num)
# now, `numbers` contains all the floating point numbers from the file
average = sum(numbers)/len(numbers)
But we can make it more efficient:
import os
import sys
fname = input('Enter the file name: ')
if not os.path.isfile(fname):
print('file cannot be opened:', fname)
sys.exit(1)
prefix = 'X-DSPAM-Confidence: '
tot = 0
count = 0
with open(fname) as infile:
for line in infile:
if not line.startswith(prefix): continue
num = line.split(":",1)[1]
tot += num
count += 1
print("The average is:", tot/count)
try this
import re
pattern = re.compile("X-DSPAM-Confidence:\s(\d+.\d+)")
sum = 0.0
count = 0
fPath = input("file path: ")
with open('fPath', 'r') as f:
for line in f:
match = pattern.match(line)
if match is not None:
lineValue = match.group(1)
sum += float(lineValue)
count += 1
print ("The average is:", sum /count)
fname = input("Enter file name: ")
fh = open(fname)
count=0
x=0
for line in fh:
if not line.startswith("X-DSPAM-Confidence:") : continue
x=float(line.split(":")[1].rstrip())+x
count=count+1
output=x/count
print("Average spam confidence:",output)

Categories