Write a program that wraps a file to a given line length - python-3.x

I am trying to get it to read the file and convert the lines to words then append the word to a line of a given length. and return the text. This is what I have so far.
def file(file_name):
''' gets users file and checks its validity'''
try:
open(file_name).readlines()
except IOError:
print('File not found')
else:
file = file_name.split()
return file
def column_length(width):
'''gets column width and checks its validity'''
try:
if int(width) >= 1:
return int(width)
else:
print('illegal value')
except ValueError:
print('Illegal value')
def main():
file_name = input('Input file name? ')
width = input('column width? ')
lines = []
line = ''
for i in file_name:
if len(i) + len(line) > int(width):
lines.append(line)
line = ''
line = line + i + ' '
if i is file_name[-1]: lines.append(line)
return '\n'.join(lines)
if __name__ == "__main__":
main()
When I run the code, it seems to skip out the first two functions and doesn't return any text.
If you know where I'm going wrong please let me know.
Thank you.

this uses a great answer from here
def chunks(l, n):
""" Yield successive n-sized chunks from l.
"""
for i in xrange(0, len(l), n):
yield l[i:i+n]
with open('in_file.txt') as in_file, open('out_file.txt', 'w') as out_file:
for in_line in in_file:
for out_line in chunks(in_line, width)
out_file.write(out_line + '\n')

Also, very interesting read is the implementation of text justification using dynamic programing. MIT has some great lecture slides online about the subject but this stack thread has most of it. It's similar to the algorithm latex uses to make all text look "pretty". It expands on your idea of text wrapping and adds the feature of justification (it adds whitespaces to make it look as best as possible).

Your code does skip the first two functions, it only defines them. You need to call them from somewhere afterwards, like you did with themain() function. There's no apparent output because the code never does anything with the lines themain()function returns (such asprintthem).
You might want to consider using Python's built-in moduletextwrapto do this sort of text processing. Here's a simple example illustrating its use:
import os
import textwrap
def get_file_name():
""" Get file name and checks its validity. """
file_name = input('Input file name? ')
if not os.path.isfile(file_name):
raise FileNotFoundError('"%s"' % file_name)
return file_name
def get_column_width():
""" Get column width and checks its validity. """
width = int(input('Column width? '))
if width < 1:
raise ValueError('column width must be greater than zero')
return width
def line_wrap(file_name, width):
""" Read blank line delimited paragraphs of text from file and wrap them to
the specified width.
"""
wrapped_lines = []
with open(file_name) as input_file:
lines = ''
for line in input_file:
lines += line
if not line.rstrip(): # blank line?
wrapped_lines.extend(textwrap.wrap(lines, width) + ['\n'])
lines = ''
if lines: # last paragraph need not be followed by blank line
wrapped_lines.extend(textwrap.wrap(lines, width))
return wrapped_lines
def main():
file_name = get_file_name()
width = get_column_width()
wrapped_lines = line_wrap(file_name, width)
print('\n'.join(wrapped_lines))
if __name__ == "__main__":
main()

Related

I'm having problems reading a csv file and inserting the words into a text box in pyqt. The words are not printing into the textbox like they should

This is the modules that are needed.
import sys
import csv
from csv import *
from PyQt4 import QtCore, QtGui, uic
qtCreatorFile = "Inquiry.ui" # Enter file here.
Ui_MainWindow, QtBaseClass = uic.loadUiType(qtCreatorFile)
class MyApp(QtGui.QMainWindow, Ui_MainWindow):
Hebrew = {'a':1,'b':2,'c':3,'d':4,'e':5,'f':6,'g':7,'h':8,'i':9,\
'j':600,'k':10,'l':20,'m':30,'n':40,'o':50,'p':60,'q':70,'r':80,\
's':90,'t':100,'u':200,'v':700,'w':900,'x':300,'y':400,'z':500}
Some other code that is important to help reproduce the problem:
Create the GUI:
def __init__(self):
"Create UI"
QtGui.QMainWindow.__init__(self)
Ui_MainWindow.__init__(self)
self.setupUi(self)
self.btnCalculate.clicked.connect(self.Calculate)
def Calculate(self):
The Event:
try:
Event = str(self.txtInquiry)
except TypeError:
pass
The Word Text File Path:
y = 'C:/Users/Jacob-C/Documents/words_alpha.txt'
These are the functions used.
Calculates the value of each word from the key mappings in the gematria system used.
def gematric_value(x, L):
value = 0
for v in x.lower():
try:
value = value + L[v]
except KeyError:
pass
return value
Modulo Function used heavily in integer reduction.
def MOD_CALC(x, y):
return (x % y)
This function takes a number and integer reduces it.
def Check_Value(x):
if x > 9 and MOD_CALC(x, 9) == 0:
return (MOD_CALC(x, 9) + 9)
elif x > 9 and MOD_CALC(x, 9) != 0:
return MOD_CALC(x, 9)
else:
return x
This is the function that does not insert the words into the plain textbox.
def Gematria(f, Hebrew, EN):
opens text file and converts it to a csv file. Then reads each word in the text file and compares the gematric value of the word and the gematric value of the event. If they match, the word is inserted to the plain text box on the qt form. This function does not do what is intended. Instead it doesn't insert anything into the plain text box.
with open(f, 'r', newline='') as input_file_name:
input_file = csv.reader(input_file_name, delimiter=' ', quotechar='|')
for word in input_file:
GV = Check_Value(gematric_value(word, L))
if GV == EN:
self.txtWords.insertPlainText(", ".join(word))
Integer reduces the Event Number
HN = gematric_value(Event, Hebrew) # Hebrew Event Number
MOD_HN = Check_Value(HN) # Reduced Hebrew Event Number
The Call:
Gematria(y, Hebrew, MOD_HN)
if __name__ == "__main__":
app = QtGui.QApplication(sys.argv)
window = MyApp()
window.show()
sys.exit(app.exec_())
Traceback (most recent call last):
File "C:\Users\Jacob-C\Documents\Numerology_Predict.py", line 146, in <module>
Launch_Program()
File "C:\Users\Jacob-C\Documents\Numerology_Predict.py", line 144, in Launch_Program
Gematria(y, L, EN)
File "C:\Users\Jacob-C\Documents\Numerology_Predict.py", line 116, in Gematria
GV = Check_Value(Event_Number(word, L))
File "C:\Users\Jacob-C\Documents\Numerology_Predict.py", line 95, in Event_Number
for e in E.lower():
AttributeError: 'list' object has no attribute 'lower'
My Answer:
def Gematria(f, L, EN):
with open(f, 'r') as input_file:
for word in input_file:
GV = Check_Value(Event_Number(word, L))
if GV == EN:
print(word)

CRUD program to read,write and append the details in txt file

It's a school assignment, an event management system. It will write the data to a txt file and retrieve it. Its mostly a CRUD program but not sure why it is not running. It shows space as an error on VS CODE IDE.
It will Create a customer, ask for the seats that he want to book. He can also delete the seats as per ref number before 24 hours.
import random
print("Welcome to the Event System")
def menu():
print("Choose the number from menu")
print("1:Create Customer")
print("2:Reserve a seat")
print("3.Cancel the seat")
print("4.Exit the Event System")
option = input("put down the number")
return option
def executingmenuinputchoice(option):
if(option == 1):
createcust()
elif(option == 2):
reserveseat()
elif(option == 3):
cancelseat()
elif(option == 4):
exit()
else:
print('you have chose a wrong option')
menu()
def createcust():
print('Provide Customer details')
name = input('Full name? --> ')
pno = input('phone number? -> ')
email = input('Email Id? --> ')
try:
file = open("cust.txt", "r")
lines = file.read().splitlines()
last_lines = lines[-1]
content = last_lines.split()
refno = random.randint(10001, 99999)
file.close()
file = open("cust.txt", "a")
file.write("\n"+" "+name+" "+pno+" "+email+" "+refno)
file.close()
print(refno + 'is your reference number')
print('Added Customer to file')
except IOError:
print("File doesn't exist at location")
except TypeError:
print('input proper data')
return createcust()
def customerexist(refno):
try:
file = open("cust.txt", "r")
for line in file:
content = line.split()
if (refno == int(content[4])):
file.close()
return True,int(content[5])
except IOError:
print("File doesn't exist")
file.close()
return False,0
def reserveseat():
referencenumber=input("Enter the Reference Number-->")
refexist =referenceexist(referencenumber)
if(refexist==True):
seatsyouwantbook=input("Number of seats you want to book? ->")
date=datetime.datetime.now()
seats=seats+seatsyouwantbook
newline=""
try:
file=open("cust.txt","r")
lines=file.read().splitlines()
last_linesno=len(lines)
currentLine=1
for line in lines:
content=line.split
if(currentline!=last_linesno):
if(refno==int(content[4])):
file.close()
return True,int(content[5])
except IOError:
print("FIle never existed")
file.close()
return False,0
def cancelseat():
try:
file=open("cust.txt","r")
for line in file:
content=line.split()
if (refno==int(content[4])):
file.close()
return True,int(content[5])
except IOError:
print("File doesn't exist")
file.close()
return False,0
invalid syntax (<unknown>, line 41)
I want it to run properly so, I can submit it again.
I haven't checked your whole code, but at least got it running to the point that you could further rectify it:-
import random
print("Welcome to the Event System")
def customerexist(refno):
try:
file = open("cust.txt", "r")
for line in file:
content = line.split()
if (refno == int(content[4])):
file.close()
return True,int(content[5])
except IOError:
print("File doesn't exist")
file.close()
return False,0
def reserveseat():
referencenumber=input("Enter the Reference Number-->")
refexist =referenceexist(referencenumber)
if(refexist==True):
seatsyouwantbook=input("Number of seats you want to book? ->")
date=datetime.datetime.now()
seats=seats+seatsyouwantbook
newline=""
try:
file=open("cust.txt","r")
lines=file.read().splitlines()
last_linesno=len(lines)
currentLine=1
for line in lines:
content=line.split
if(currentline!=last_linesno):
if(refno==int(content[4])):
file.close()
return True,int(content[5])
except IOError:
print("FIle never existed")
file.close()
return False,0
def cancelseat():
try:
file = open("cust.txt","r")
for line in file:
content=line.split()
if (refno==int(content[4])):
file.close()
return True,int(content[5])
except IOError:
print("File doesn't exist")
file.close()
return False,0
def createcust():
print('Provide Customer details')
name = input('Full name? --> ')
pno = input('phone number? -> ')
email = input('Email Id? --> ')
try:
file = open("cust.txt", "r")
lines = file.read().splitlines()
last_lines = lines[-1]
content = last_lines.split()
refno = random.randint(10001, 99999)
file.close()
file = open("cust.txt", "a")
file.write("\n"+" "+name+" "+pno+" "+email+" "+refno)
file.close()
print(refno + 'is your reference number')
print('Added Customer to file')
except IOError:
print("File doesn't exist at location")
except TypeError:
print('input proper data')
return createcust()
def menu():
print("Choose the number from menu")
print("1:Create Customer")
print("2:Reserve a seat")
print("3.Cancel the seat")
print("4.Exit the Event System")
option = input("put down the number")
return option
def executingmenuinputchoice(option):
option = int(option)
if(option == 1):
createcust()
elif(option == 2):
reserveseat()
elif(option == 3):
cancelseat()
elif(option == 4):
exit()
else:
print('you have chose a wrong option')
menu()
executingmenuinputchoice(menu())
REASON FOR ERRORS:-
Your indentation was all over the place, python language
prioritizes indentation as it uses it to figure out a block span, so you should
keep a consistent indentation scheme throughout your code.
Python uses top down approach for ~interpreting the
program, i.e. It only keeps track of the stuff that it had already
encountered. In your code, the function executingmeninputchoice()
and menu() (the two primary functions used for UI) were stacked
above all other function, therefore when you tried to call other
function from these two function, they aren't called. As the program
doesn't know whether these functions exists or not (as it hasn't
encountered them yet)
A logical error existed in function
executingmenuinputchoice(option) as you were trying to take in
input a string and were comparing it with integer values, and
therefore every time the operation failed and the control got shifted
to the else block, therefore every time you got the same output
'you have chose a wrong option' regardless of whether the input was
legal or not
P.S.:- I haven't tested your full code, as this isn't a code for me service, other logical errors may also exist, so I would recommend you to find and fix those too.

How to print all the highest value places

I cannot figure out how to get python to print all the highest values as it only prints the first one it encounters.
It takes standard input from a file that has on a few lines the following:
89 Michael Dunne (grade name)
I know I can use the zip function but I cannot figure out how only print the name from it
If I add "highstudents = sorted(zip(grade,name),reverse=True)" it sorts from high to low but I do not know how to filter the name out as it prints as "(89, 'Pepe')"
The code below is the following attempt so far.
import sys
def topgrade(x):
s = max(x)
return s
def main():
s = sys.argv[1]
grade=[]
name = []
try:
with open(s,'r') as studata:
for line in studata:
try:
line = line.strip()
grade.append(int(line[0:2]))
name.append(line[3::])
except ValueError:
print("Invalid mark",line[0:2],"encountered. Skipping.")
top = topgrade(grade)
a = grade.index(top)
print("Best students:",name[a])
print("Best mark:",top)
except FileNotFoundError:
print("File not found:",s)
if __name__ == '__main__':
main()
Rather than trying to keep the students and marks in 2 separate lists (with the risk that they get out of step) it is better to use a dictionary - where the key is the mark and the value is a list of the student(s) who obtained that mark.
Then it is a simple task of just printing out the highest key, and the associated list of students. I'm using defaultdict as an easier option than having to create or append to the list for each value.
from collections import defaultdict
import sys
def main():
s = sys.argv[1]
grades = defaultdict(list)
try:
with open(s,'r') as studata:
for line in studata:
try:
line = line.strip()
grades[int(line[0:2])].append(line[3::])
except ValueError:
print("Invalid mark",line[0:2],"encountered. Skipping.")
top_mark = max(grades.keys())
print("Best students:{}".format(','.join(grades[top_mark])))
print("Best mark: {}".format(top_mark))
except FileNotFoundError:
print("File not found:",s)
if __name__ == '__main__':
main()

Program to search through a file and find matches with deletion words

My code doesnt do what it is supposed to. It is meant to search through the text file and print words that match with the deletion words created from removing a letter from a given word
import math as m
def check_deletions(str,fd):
count=0
for int in range(len(str)):
delWord=str[:int]+str[int+1:]
doubleChecker=False
for i in range(int+1,len(str)-1):
if delWord==str[:i]+str[i+1:]:
doubleChecker=True
if doubleChecker==True:
doubleChecker=False
else:
for line in fd:
if delWord==line.strip():
print(delWord)
print("Found ",count," deletions")
def main():
file=open("long-word-list.txt")
check_deletions("baag",file)
file.close()
main()

Functions and Dictionary in Python

def build_dictionary(infile):
count_dict={}
for line in infile:
line=line.strip()
if len(line) and line[0]!="-":
lst=line.split(",")
lastname=lst[0].strip()
for lastname in lst:
if lastname not in count_dict:
count_dict[lastname]=1
else:
count_dict[lastname]=count_dict[lastname]+1
return count_dict
def main():
import os.path
while True:
try:
name1=input("Enter input name:")
infile=open(name1,"r")
result=build_dictionary(infile)
print(result)
break
except:
print("Error in code")
main()
I have this program and I want it to take a file that contains last name,first name, take the last names and see how many times they appear in the dict. the only problem i have is it counts the first lastname then stops, whyy isnt it going through the entire dictionary
Replace your build_dictionary method with this:
def build_dictionary(infile):
count_dict={}
for line in infile:
line=line.strip()
if len(line) and line[0]!="-":
lst=line.split(",")
lastname=lst[0].strip()
if lastname not in count_dict:
count_dict[lastname]=1
else:
count_dict[lastname]=count_dict[lastname]+1
return count_dict

Resources