Appending Words to a list - python

I am trying to append the incorrect words to a list, however when I print the list outside of the function it is empty and when I print it inside the function it prints a list for each word. How do I get the list to print just one time with the incorrect words in it at the end of the program?
File 1:
this is my spell checker program
File 2: dis is my spll cheker program
So there are 3 incorrect words that should be added to the list
word_list = []
if cmdlength != 2:
print ("Usage error, expected 2 args got " + str(cmdlength))
exit()
else:
try:
f = open(sys.argv[1])
f.close()
except FileNotFoundError:
print("File does not exist")
exit()
try:
ff = open(sys.argv[2])
ff.close()
except FileNotFoundError:
print("File does not exist")
exit()
word = ""
with open(sys.argv[1],"r") as fh:
while True:
ch=fh.read(1)
if ch == " " or ch == "\n" or ch == ":" or ch == ".":
with open(sys.argv[2],"r") as fh2:
def check_word(word,fh2,word_list):
lines = fh2.readlines()
for line in lines:
x= re.search(word,line)
if x:
#correctwords
print(word + ": " + "0")
#count += 1
else:
#incorrect words
print(word, ": " , "1")
word_list.append(word)
#count2 += 1
check_word(word,fh2,word_list)
word = ''
else:
word += ch
if not ch:
print(word)
print("End of file")
print(word_list)
break

The function is missing a return statement to return word_list.
This should work
...
def check_word(word,fh2,word_list):
lines = fh2.readlines()
for line in lines:
...
word_list.append(word)
#count2 += 1
return word_list
word_list = check_word(word,fh2,word_list)

Related

Python reverse each word in a sentence without inbuilt function python while preserve order

Not allowed to use "Split(),Reverse(),Join() or regexes" or any other
helping inbuilt python function
input something like this:
" my name is scheven "
output like this:
"ym eman si nevehcs"
you need to consider removing the starting,inbetween,ending spaces aswell in the input
I have tried 2 tries, both failed i will share my try to solve this and maby an idea to improve it
First try:
def reverseString(someString):
#lenOfString = len(someString)-1
emptyList = []
for i in range(len(someString)):
emptyList.append(someString[i])
lenOfString = len(emptyList)-1
counter = 0
while counter < lenOfString:
if emptyList[counter] == " ":
counter+=1
if emptyList[lenOfString] == " ":
lenOfString-=1
else:
swappedChar = emptyList[counter]
emptyList[counter] = emptyList[lenOfString]
emptyList[lenOfString] = swappedChar
counter+=1
lenOfString-=1
str_contactantion = ""
#emptyList = emptyList[::-1]
#count_spaces_after_letter=0
for letter in emptyList:
if letter != " ":
str_contactantion+=letter
#str_contactantion+=" "
str_contactantion+=" "
return str_contactantion
second try:
def reverse(array, i, j):
emptyList = []
if (j == i ):
return ""
for k in range(i,j):
emptyList.append(array[k])
start = 0
end = len(emptyList) -1
if start > end: # ensure i <= j
start, end =end, start
while start < end:
emptyList[start], emptyList[end] = emptyList[end], emptyList[start]
start += 1
end -= 1
strconcat=""
for selement in emptyList:
strconcat+=selement
return strconcat
def reverseStr(someStr):
start=0
end=0
help=0
strconcat = ""
empty_list = []
for i in range(len(someStr)):
if(someStr[i] == " "):
continue
else:
start = i
j = start
while someStr[j] != " ":
j+=1
end = j
#if(reverse(someStr,start,end) != ""):
empty_list.append(reverse(someStr,start,end))
empty_list.append(" ")
for selement in empty_list:
strconcat += selement
i = end + 1
return strconcat
print(reverseStr(" my name is scheven "))
The following works without managing indices:
def reverseString(someString):
result = crnt = ""
for c in someString:
if c != " ":
crnt = c + crnt # build the reversed current token
elif crnt: # you only want to do anything for the first space of many
if result:
result += " " # append a space first
result += crnt # append the current token
crnt = "" # and reset it
if crnt:
result += " " + crnt
return result
reverseString(" my name is scheven ")
# 'ym eman si nevehcs'
Try this:
def reverseString(someString):
result = ""
word = ""
for i in (someString + " "):
if i == " ":
if word:
result = result + (result and " ") + word
word = ""
else:
word = i + word
return result
You can then call it like this:
reverseString(" my name is scheven ")
# Output: 'ym eman si nevehcs'
Try this:
string = " my name is scheven "
def reverseString(someString):
result = ''
curr_word = ''
for i in someString:
if i == ' ':
if curr_word:
if result:
result = f'{result} {curr_word}'
else:
result = f'{result}{curr_word}'
curr_word = ''
else:
curr_word = f'{i}{curr_word}'
return result
print(repr(reverseString(string)))
Output:
'ym eman si nevehcs'
Note: if you're allowed to use list.append method, I'd suggest using a collections.deque as it's more performant than appending to a list. But of course, in the end you'll need to join the list together, and you mentioned that you're not allowed to use str.join, so that certainly poses an issue.

How to add a while true loop to count how many times a word was said in the text?

I'm trying to use dictionary and some loops to figure out how many times a word was written and if user types in "quit" then the program should stop. This is what I have so far:
import string
text = open('text.txt', 'r')
val = dict()
for i in text:
i = i.strip().lower().split(" ")
print(i)
This is one approach to the problem:
with open('text.txt', 'r') as file:
data = file.read()
data = data.replace('\n', ' ')
data = data.split(' ')
while True:
counter = 0
search_term = input('Word: ')
if search_term == 'quit':
break
for word in data:
if word.lower() == search_term.lower() or word.lower() == search_term.lower() + '.':
counter += 1
if counter == 0:
print('None found!')
else:
print(f'Number of "{search_term}": {counter}')

Python dictionary if/else invalid syntax

I cant figure out why line 104 keeps returning invalid syntax, can someone please point me in the right direction? Does it have something to do with the way i used elif? Sorry if this is a newbie question!
Line 104 is the else statement in the for item in workingDict.keys() loops inside printGrammar
import sys
import string
from collections import defaultdict
#default length of 3
stringLength = 3
#get last argument of command line(file)
if len(sys.argv) == 1:
#get a length from user
try:
stringLength = int(input('Length? '))
filename = input('Filename: ')
except ValueError:
print("Not a number")
elif len(sys.argv) == 2:
#get a length from user
try:
stringLength = int(input('Length? '))
filename = sys.argv[1]
except ValueError:
print("Not a number")
elif len(sys.argv) == 3:
filename = sys.argv[2]
stringLength = sys.argv[1].split('l')[1]
else:
print("Invalid input!")
#get start symbol
with open(filename, "r") as grammar:
#read file
lines = grammar.readlines()
start = lines[0].split('=')[0]
start = start.replace(" ", "")
#checks
#print(stringLength)
#print(filename)
#print(start)
def str2dict(filename):
result = defaultdict(list)
with open(filename, "r") as grammar:
#read file
lines = grammar.readlines()
count = 0
#loop through
for line in lines:
#append info
line = line.rstrip()
result[line[0]].append(line.split('=')[1])
return result
workingDict = str2dict("Binary.txt")
print(workingDict)
def printGrammar(result):
sentenceList = []
workList = []
workList.append(start)
i = 0
firstNT = ""
#While the worklist is not empty:
while(len(workList) != 0):
#Get and delete one potential sentence s from the worklist.
symbol = workList.pop()
#If the | s | > N, continue.
if len(str(symbol).replace(" ", "")) > int(stringLength):
continue
else:
if str(symbol) in workingDict.keys():
#append the right derivation
for item in workingDict.get(symbol):
workList.append(list(item.replace(" ", "")))
#workList.append(str(workingDict.get(symbol)))
#add derivation
print(workingDict.keys())
#If s has no nonterminals, print s and continue.
for item in workingDict.keys():
print("test")
print(''.join(item))
if len(item) != 1:
continue
#if the element is in dictionary, dont print
elif ''.join(item) in workingDict.keys():
continue
print(symbol)
#if element is not in dictionary, print
else:
print("THIS IS A TERMINAL!!")
print(item)
#Choose the leftmost nonterminal NT.
print(workList)
#For all productions NT -> rhs:
#Replace NT in s with rhs; call it tmp.
#Store tmp on worklist.
return workList
print (printGrammar(workingDict))
You need to indent the line
print(symbol)
to the same level as continue.

Python: How to retrieve second word from the text

So the generator function generates a word char by char until "" and now I want the main function to call out generator function 100 times so that it would create a list words with 100 words. As I have it now it will call out the function 100x but only with one word. What should I do so that it would remember the words it has used already.
word = " "
def generator():
global word
with open("text.txt", "r") as file:
file.read(1)
for line in file:
for char in line:
if char != " ":
word += char
if char == " ":
return
def main():
words = []
for i in range(100):
generator()
words.append(word)
print(words)
if __name__ == '__main__':
main()
def word_generator():
word = ""
with open("text.txt", "r") as file:
file.read(1)
for line in file:
for char in line:
if char != " ":
word += char
if char == " ":
yield word
word = ""
that is now a generator
it is used like this
for word in word_generator():
print word
if you only want the first hundred you could do
for i,word in enumerate(word_generator()):
if i > 100:
break
print word
print "Last Word:",word
You can create a generator with yield, and manipulate the generator as you needed (say stop at 100).
def make_generator():
with open("text.txt", "r") as f:
for line in f:
for word in line.split():
yield word
def main():
words = []
generator = make_generator()
for i in range(100):
w = next(generator)
words.append(w)
print(words)
if __name__ == '__main__':
main()

Python Palindrome Try and Except not printing

My except won't print when len(line.strip()) == d gets None.
def isPalindrome(word):
if len(word) < 1:
return True
else:
if word[0] == word[-1]:
return isPalindrome(word[1:-1])
else:
return False
def fileInput(filename):
palindromes = False
fh = open(filename, "r")
length = input("Enter length of palindromes:")
d = int(length)
try:
for line in fh:
for s in str(len(line)):
if isPalindrome(line.strip()):
palindromes = True
if (len(line.strip()) == d):
print(line.strip())
except:
print("No palindromes found for length entered.")
finally:
fh.close()
Your code is failing because your exception is not the only place where non-existence of d-length palindromes in your input file takes you.
You need to check for the value of palindromes as well.
So, at the end of your try-block, add a line that prints "no palindromes found", like so:
def fileInput(filename):
palindromes = False
# more code
try:
# more code
if not palindromes:
print("No palindromes found for length entered.")
except:
print("No palindromes found for length entered.")
finally:
# more code
By the way, I would clean up your function as follows:
def isPalindrome(word):
if not len(word): # is the same as len(word) == 0
return True
elif word[0] == word[-1]: # no need for overly nested if-else-blocks
return isPalindrome(word[1:-1])
else:
return False
def fileInput(filename):
palindromes = False
d = int(input("Enter length of palindromes:"))
with open(filename) as fh: # defaults to "r" mode. Also, takes care of closing the file for you
for line in fh:
word = line.strip()
if isPalindrome(word) and len(word) == d: # note that you didn't have the len(word)==d check before. Without that, you don't check for the length of the palindrome
palindromes = True
print(word)
if not palindromes:
print("No palindromes found for length entered.")

Categories