What is wrong with this program? Why did number and totalLength 0? - python-3.x

why is it that the number and totalLength still 0? What am I doing wrong. It should have changed due to the for line in lines statement
def cleanedup(s):
alphabet= 'abcdefghijklmnopqrstuvwxyz'
cleantext = ''
for character in s.lower():
if character in alphabet:
cleantext += character
else:
cleantext = ' '
return cleantext
import shelve
shelf = shelve.open('books')
lines = shelf['Pride and Prejudice']
shelf.close()
number = 0
totalLength = 0
for line in lines:
for word in cleanedup(line).split():
number += 1
totalLength += len(word)
print(totalLength, number)

This is the main problem with your script:
for character in s.lower():
...
else:
cleantext = ' '
I'm not sure this is the right position for the else, in your case you've put it after the for loop, so cleantext will be reset each time you run this function because your for loop has no break statement inside. More info on for ... else ...
Although that might not be what you want (question is a little unclear), the following code works:
def cleanedup(s):
alphabet= 'abcdefghijklmnopqrstuvwxyz'
cleantext = ''
for character in s.lower():
if character in alphabet:
cleantext += character
return cleantext
lines = ['lorem ipsum dolor sin amet', 'foo bar']
number = 0
totalLength = 0
for line in lines:
for word in cleanedup(line).split():
number += 1
totalLength += len(word)
print(totalLength, number)
Output:
>>> 28 2 # 28 = total number of characters, 2 = total number of lines
PS: Next time, provide a more concise example that demonstrates the problem, instead of using an external file.

Related

how to move a character to a certain inputted index

I am trying to make my own text editor where it asks for a file and prints a > that can then be moved to the specified index of the line so that it can then delete a character. I don't know the best way to move it. So far I have
def print_file(data, cursor):
"""Prints the file contents (data), with the cursor in the right place."""
# Variable fm will store the formatted representation
# of the file with position information, etc.
fm = ""
pos = 0
# Break the "file" (represented by a string) up into lines.
lines = data.split("\n")
for x, line in enumerate(lines):
length = len(line)
if length != 0:
# Edge case for the end of the "file".
if data[-1] != "\n" and x == len(lines) - 1:
length -= 1
fm += str("{0:70} |{1:3d}:{2:3d}|\n".format(line, pos, pos + length))
# If the cursor points to char on this line add it.
if pos <= cursor <= pos + length:
fm += " " * (cursor - pos) + "^\n"
# Start at the next character.
pos += length + 1
print(fm, end="")
#end of function
def move_cursor(location):
"""Moves the cursor to the right location"""
#end of function
cursor = 0
is_open = False
is_modified = False
file = str(input(">open "))
#Open filename
file == "(filename)"
file = open(file, "r")
file_data = file.read()
print_file(file_data, cursor)
command = str(input("> "))
#Move position
if command == "move(int)":
move_cursor(location)
I think the best way would be to make a function and then call it inside the loop, but am unsure how to actually get it to move to the index....

Caesar Cipher shift on new lines

I am having a problem with my code trying to do an advanced caesar cipher shift. I changed a certain letter to another, and then added a string to certain parts of a file before encoding, but am having problems doing the shifting now. This is my code:
import string
import sys
count = 1
cont_cipher = "Y"
#User inputs text
while cont_cipher == "Y":
if count == 1:
file = str(input("Enter input file:" ""))
k = str(input("Enter shift amount: "))
purpose = str(input("Encode (E) or Decode (D) ?: "))
#Steps to encode the message, replace words/letter then shift
if purpose == "E":
my_file = open(file, "r")
file_contents = my_file.read()
#change all "e"s to "zw"s
for letter in file_contents:
if letter == "e":
file_contents = file_contents.replace(letter, "zw")
#add "hokie" to beginning, middle, and end of each line
lines = file_contents.split('\n')
def middle_message(lines, position, word_to_insert):
lines = lines[:position] + word_to_insert + lines[position:]
return lines
new_lines = ["hokie" + middle_message(lines[x], len(lines[x])//2, "hokie") + "hokie" for x in range(len(lines))]
#math to do the actual encryption
def caesar(word, shifts):
word_list = list(new_lines)
result = []
s = 0
for c in word_list:
next_ord = ord(c) + s + 2
if next_ord > 122:
next_ord = 97
result.append(chr(next_ord))
s = (s + 1) % shifts
return "".join(result)
if __name__ == "__main__":
print(caesar(my_file, 5))
#close file and add to count
my_file.close()
count = count + 1
The error I am getting is:
TypeError: ord() expected a character, but string of length 58 found
I know that I need to split it into individual characters, but am not sure how to do this. I need to use the updated message and not the original file in this step...

Print Word & Line Number Where Word Occurs in File Python

I am trying to print the word and line number(s) where the word occurs in the file in Python. Currently I am getting the correct numbers for second word, but the first word I look up does not print the right line numbers. I must iterate through infile, use a dictionary to store the line numbers, remove new line chars, remove any punctuation & skip over blank lines when pulling the number. I need to add a value that is actually a list, so that I may add the line numbers to the list if the word is contained on multiple lines.
Adjusted code:
def index(f,wordf):
infile = open(filename, 'r')
dct = {}
count = 0
for line in infile:
count += 1
newLine = line.replace('\n', ' ')
if newLine == ' ':
continue
for word in wordf:
if word in split_line:
if word in dct:
dct[word] += 1
else:
dct[word] = 1
for word in word_list:
print('{:12} {},'.format(word,dct[word]))
infile.close()
Current Output:
>>> index('leaves.txt',['cedars','countenance'])
pines [9469, 9835, 10848, 10883],
counter [792, 2092, 2374],
Desired output:
>>> index2('f.txt',['pines','counter','venison'])
pines [530, 9469, 9835, 10848, 10883]
counter [792, 2092, 2374]
There is some ambiguity for how your file is set up, but I think it understand.
Try this:
import numpy as np # add this import
...
for word in word_f:
if word in split_line:
np_array = np.array(split_line)
item_index_list = np.where(np_array == word)
dct[word] = item_index_list # note, you might want the 'index + 1' instead of the 'index'
for word in word_f:
print('{:12} {},'.format(word,dct[word]))
...
btw, as far as I can tell, you're not using your 'increment' variable.
I think that'll work, let me know if it doesn't and I'll fix it
per request, I made an additional answer (that I think works) without importing another library
def index2(f,word_f):
infile = open(f, 'r')
dct = {}
# deleted line
for line in infile:
newLine = line.replace('\n', ' ')
if newLine == ' ':
continue
# deleted line
newLine2 = removePunctuation(newLine)
split_line = newLine2.split()
for word in word_f:
count = 0 # you might want to start at 1 instead, if you're going for 'word number'
# important note: you need to have 'word2', not 'word' here, and on the next line
for word2 in split_line: # changed to looping through data
if word2 == word:
if word2 in dct:
temp = dct[word]
temp.append(count)
dct[word] = temp
else:
temp = []
temp.append(count)
dct[word] = temp
count += 1
for word in word_f:
print('{:12} {},'.format(word,dct[word]))
infile.close()
Do be aware, I don't think this code will handle if the words passed in are not in the file. I'm not positive on the file that you're grabbing from, so I can't be sure, but I think it'll seg fault if you pass in a word that doesn't exist in the file.
Note: I took this code from my other post to see if it works, and it seems that it does
def index2():
word_list = ["work", "many", "lots", "words"]
infile = ["lots of words","many many work words","how come this picture lots work","poem poem more words that rhyme"]
dct = {}
# deleted line
for line in infile:
newLine = line.replace('\n', ' ') # shouldn't do anything, because I have no newlines
if newLine == ' ':
continue
# deleted line
newLine2 = newLine # ignoring punctuation
split_line = newLine2.split()
for word in word_list:
count = 0 # you might want to start at 1 instead, if you're going for 'word number'
# important note: you need to have 'word2', not 'word' here, and on the next line
for word2 in split_line: # changed to looping through data
if word2 == word:
if word2 in dct:
temp = dct[word]
temp.append(count)
dct[word] = temp
else:
temp = []
temp.append(count)
dct[word] = temp
count += 1
for word in word_list:
print('{:12} {}'.format(word, ", ".join(map(str, dct[word])))) # edited output so it's comma separated list without a trailing comma
def main():
index2()
if __name__ == "__main__":main()
and the output:
work 2, 5
many 0, 1
lots 0, 4
words 2, 3, 3
and the explanation:
infile = [
"lots of words", # lots at index 0, words at index 2
"many many work words", # many at index 0, many at index 1, work at index 2, words at index 3
"how come this picture lots work", # lots at index 4, work at index 5
"poem poem more words that rhyme" # words at index 3
]
when they get appended in that order, they get the correct word placement position
My biggest error was that I was not properly adding the line number to the counter. I completely used the wrong call, and did nothing to increment the line number as the word was found in the file. The proper format was dct[word] += [count] not dct[word] += 1
def index(filename,word_list):
infile = open(filename, 'r')
dct = {}
count = 0
for line in infile:
count += 1
newLine = line.replace('\n', ' ')
if newLine == ' ':
continue
newLine2 = removePunctuation(newLine)
split_line = newLine2.split()
for word in word_list:
if word in split_line:
if word in dct:
dct[word] += [count]
else:
dct[word] = [count]
for word in word_list:
print('{:12} {}'.format(word,dct[word]))
infile.close()

Printing integers tiled horizontally - Python3

I'm trying to obtain the following: i want to print a range of integers, but if the integer contains more than 10 digits, the '1' in '10' needs to be printed on top.
e.g.:
6 - > 123456
13 - >...................1111
..........1234567890123
Remark, that if it contains less then 10 digits, there's no 'upper line' printed. And the '.' should be replaced just by spaces, but the editor won't let me do that
I've tried the following:
line10 = ''
line1 = ''
if length > 10:
for i in range(length):
if (i + 1) // 10 == 0:
line10 += ' '
else:
line10 += str((i + 1) // 10)
for i in range(length):
line1 += str((i + 1) % 10)
if length > 10:
print(line10)
print(line1)
And: this works, but how can you make it work for let's say 100 or 1000, without having to copy the lines of code?
Thanks in advance.
There may be a more elegant solution to your problem, but I believe this does what you require:
def number_printer(n):
lines = [[] for m in range(len(str(n)))]
for i in range(1, n+1):
diff = len(str(n))-len(str(i))
if diff > 0:
for z in range(diff):
lines[z].append(" ")
for x, y in enumerate(str(i)):
lines[x+diff].append(y)
else:
for x, y in enumerate(str(i)):
lines[x].append(y)
for line in lines:
print "".join(line)
if __name__ == "__main__":
number_printer(132)
Essentially, it is checking the length of each number it counts through against the lenght of the number you wish to print (in this example 132). Wherever it finds a difference (where diff > 0), it appends the appropriate number of blank spaces so all the numbers align (e.g. for the number 12 it would append 1 blank space, as the difference in length between 12 and 132 is 1).
Hopefully this is what you were after!

Duplicate word in hangman game Python

I have a problem, when in Hangman game there is a word like happy, it only append 1 'p' in the list...run my code and please tell me what to do?
check my loops.
import random
import time
File=open("Dict.txt",'r')
Data = File.read()
Word = Data.split("\n")
A = random.randint(0,len(Word)-1)
Dict = Word[A]
print(Dict)
Dash = []
print("\n\n\t\t\t","_ "*len(Dict),"\n\n")
i = 0
while i < len(Dict):
letter = str(input("\n\nEnter an alphabet: "))
if letter == "" or letter not in 'abcdefghijklmnopqrstuvwxyz' or len(letter) != 1:
print("\n\n\t\tPlease Enter Some valid thing\n\n")
time.sleep(2)
i = i - 1
if letter in Dict:
Dash.append(letter)
else:
print("This is not in the word")
i = i - 1
for item in Dict:
if item in Dash:
print(item, end = " ")
else:
print("_", end = " ")
i = i + 1
The error is with the "break" on Line 25: once you have filled in one space with the letter "p", the loop breaks and will not fill in the second space with "p".
You need to have a flag variable to remember whether any space has been successfully filled in, like this:
success = False
for c in range(len(Dict)):
if x == Dict[c]:
Dash[c] = x
success = True
if not success:
Lives -= 1
P.S. There's something wrong with the indentation of the code you have posted.

Resources