I have a starting file which has values on each line separated by a comma, like so:
hello,welcome
hi, howareyou
hola,comoestas
I want to take those words and put them into a dictionary so they are key/value pairs. Then i am trying to ask for a key and return the corresponding value. I believe i am close so any help would be appreciated. Also i am a beginner so simple code is best.
def CreateDictionary():
WordDictionary = open('file.csv', 'r')
for line in WordDictionary:
mylist = line.split(',')
return(mylist)
def main():
cd = CreateDictionary()
text=input('input text:')
for x in cd.values():
if x == text:
word=cd[x]
print(word)
main()
def makeDict(infilepath):
answer = {}
with open(infilepath) as infile:
for line in infile:
key,val = line.strip().split(',')
answer[key] = val
return answer
def main(infilepath):
cd = makeDict(infilepath)
key = input('input text: ')
if key in cd:
print(cd[key])
else:
print("'%s' is not a known word" %key)
Here's a way you could edit your solution to create a dictionary.
def CreateDictionary():
ret_dict = {}
with open('file.csv', 'r') as WordDictionary:
for line in WordDictionary:
parts = line.split(',')
ret_dict[parts[0]] = parts[1]
return ret_dict
def main():
cd = CreateDictionary()
text = raw_input('input text:')
word = cd[text]
print word
main()
A main issue with your approach is that you have return inside of a for loop. The function will return after the first loop iteration and will not continue beyond the first line of the file.
Related
I want to pass a dictionary between two functions, but how to do this without using a global variable?
I'm trying to pass the dictionary that is in my "fileProcessing" function into the "swappingKandV_PrintingResults" function without having a global variable being modified.
dictionary = dict()
fileinputname = input("Please Input File Name: ")
try:
filehandling = open(fileinputname)
except:
print("Invalid Entry")
quit()
rawfile = filehandling.readlines()
def fileProcessing(rawfile):
for iteration in(range(len(rawfile))):
rawfile[iteration] = rawfile[iteration].lower()
for line in rawfile:
line.rstrip()
line.split()
for words in line:
letter = words.split()
for iteration in letter:
if iteration.isalpha() :
dictionary[iteration] = dictionary.get(iteration, 0) + 1
def swappingKandV_PrintingResults(dictionary):
finalresults = []
for (k,v) in dictionary.items():
newtuple = (v, k)
finalresults.append(newtuple)
finalresults = sorted(finalresults, reverse=True)
for iteration in finalresults:
print(iteration)
fileProcessing(rawfile)
swappingKandV_PrintingResults(dictionary)
By making the first function create and return the dictionary. Then pass that returned dictionary to the second function.
fileinputname = input("Please Input File Name: ")
try:
filehandling = open(fileinputname)
except:
print("Invalid Entry")
quit()
rawfile = filehandling.readlines()
def fileProcessing(rawfile):
dictionary = {}
for iteration in(range(len(rawfile))):
rawfile[iteration] = rawfile[iteration].lower()
for line in rawfile:
line.rstrip()
line.split()
for words in line:
letter = words.split()
for iteration in letter:
if iteration.isalpha() :
dictionary[iteration] = dictionary.get(iteration, 0) + 1
return dictionary
def swappingKandV_PrintingResults(dictionary):
finalresults = []
for (k,v) in dictionary.items():
newtuple = (v, k)
finalresults.append(newtuple)
finalresults = sorted(finalresults, reverse=True)
for iteration in finalresults:
print(iteration)
swappingKandV_PrintingResults(fileProcessing(rawfile))
From the way you phrased the question, it seems you have some confusion on how to work with passing arguments to functions and how to handle scope. I would suggest having at look at what a variable is in Python to begin with and then what passing it to a function means.
You can accomplish this task in 2 ways:
1. Nested Function Call :
If you want to necessarily call 2nd function after 1st, just write -
'swappingKandV_PrintingResults(dictionary)' as the ending line in the fileProcessing function.
2. Accepting Return from 1st and Passing as Argument to 2nd :
As insisted by #Reti43 too, just write -
'return dictionary' as the ending line in the fileProcessing function and replace your last 2 lines of code by -
Dict = fileProcessing(rawfile)
swappingKandV_PrintingResults(Dict)
Hello hopefully someone can steer me in the right direction.
I am trying to figure out how use def function to modify lines of text in a list according to user input. eg if user enters "a", it adds a line to the list, "d" = delete line and so on...
I have defined the functions and know what they have to do, here is some of it:
lineList = []
lines = ""
##Add Line
def addLine ():
while lines != "#":
lines = input ("Add a line: ")
lineList.append(lines)
for (i, item) in enumerate(lineList, start=1):
print(str(i)+":", item)
##Delete Line
def deleteLine ():
lineNum = int(input("Enter line: ") )
del lineList[(lineNum)]
for (i, item) in enumerate(lineList, start=1):
print(str(i)+":", item)
##Find and replace string
def findReplace ():
findString = input("Find string: ")
replaceString = input ("Replace with: ")
for n, i in enumerate(lineList):
if i == findString:
lineList[n] = replaceString
for (i, item) in enumerate(lineList, start=1):
print(str(i)+":", item)
So I am trying to find out: should the initial list be inside addLine () or outside it? Should I use addLine() to just append the list? Also how do the other functions access the list to make changes?
You can make the functions accept the current lineList as a parameter and return it back after changes. For example:
##Add Line
def addLine(lineList):
lines = ""
while lines != "#":
lines = input ("Add a line: ")
lineList.append(lines)
for (i, item) in enumerate(lineList, start=1):
print(str(i)+":", item)
return lineList
##Delete Line
def deleteLine(lineList):
lineNum = int(input("Enter line: "))
del lineList[(lineNum)]
for (i, item) in enumerate(lineList, start=1):
print(str(i)+":", item)
return lineList
##Find and replace string
def findReplace(lineList):
findString = input("Find string: ")
replaceString = input ("Replace with: ")
for n, i in enumerate(lineList):
if i == findString:
lineList[n] = replaceString
for (i, item) in enumerate(lineList, start=1):
print(str(i)+":", item)
return lineList
lineList = []
while True:
command = input("Enter command (a, d, f): ")
if command == "a":
lineList = addLine(lineList)
elif command == "d":
lineList = deleteLine(lineList)
elif command == "f":
lineList = findReplace(lineList)
From what i understood what u are trying to do u need to have the linelist variable outside the functions so it is a global variable and then u can access it from everywhere even inside functions. if u declare that variable inside the function add u will need to add at the beginning of the add function:
def addLine ():
global linelist
linelist = []
while lines != "#":
lines = input ("Add a line: ")
lineList.append(lines)
for (i, item) in enumerate(lineList, start=1):
print(str(i)+":", item)
this way the variable is global aswell, but it is easier to use it just outside the function.
hope this helps :D
It's better if you just make your functions take the list as function parameters. It's generally bad practice to use global variables, and you should avoid them whenever possible. That way, your functions can be self-contained and independant, which is a good design trait. So, just make it an argument instead.
Also, the following block of code is redundant in every function of yours. It'd be better if you just encapsulate it inside of a function too.
for (i, item) in enumerate(lineList, start=1):
print(str(i)+":", item)
For example:
def print_lines(line_list):
for (i, item) in enumerate(lineList, start=1):
print(str(i)+":", item)
This way, you don't have to worry about the for loop everytime, and can just have print_lines(line_list) in your functions instead.
Protip: Have a look at the PEP-8 Style Guide. This PEP will give you some insight on how you should style your code.
Hope the answer helped :)
I'm writing a program which takes the input string and prints out all anagrams of the string, from a text file, in a list.
So far, I've got the following; but nothing is returned and I don't quite understand why.
def anagrams( s1, s2 ):
s1_list = list(s1.lower())
s1_list.sort()
s2_list = list(s2.lower())
s2_list.sort()
if s1.lower() == s2.lower():
return(False)
elif s1_list == s2_list:
return(True)
else:
return(False)
def find_all_anagrams( string ):
anagrams_list = []
with open("english_words.txt", "r") as fileObject:
line = fileObject.readline()
if anagrams(string, line):
anagrams_list.append(line)
return anagrams_list
You need to iterate through all the words (I'm assuming one per line) in english_words.txt. You also need strip any newline characters from each word before you call anagrams().
def find_all_anagrams( string ):
anagrams_list = []
with open("english_words.txt", "r") as fileObject:
for line in fileObject: # check all lines
word = line.strip() # strip newline characters
if anagrams(string, word):
anagrams_list.append(word)
return anagrams_list # finally return results
I want to check if a string is in a text file. If it is, do X. If it's not, do Y. However, this code always returns True for some reason. Can anyone see what is wrong?
def check():
datafile = file('example.txt')
found = False
for line in datafile:
if blabla in line:
found = True
break
check()
if True:
print "true"
else:
print "false"
The reason why you always got True has already been given, so I'll just offer another suggestion:
If your file is not too large, you can read it into a string, and just use that (easier and often faster than reading and checking line per line):
with open('example.txt') as f:
if 'blabla' in f.read():
print("true")
Another trick: you can alleviate the possible memory problems by using mmap.mmap() to create a "string-like" object that uses the underlying file (instead of reading the whole file in memory):
import mmap
with open('example.txt') as f:
s = mmap.mmap(f.fileno(), 0, access=mmap.ACCESS_READ)
if s.find('blabla') != -1:
print('true')
NOTE: in python 3, mmaps behave like bytearray objects rather than strings, so the subsequence you look for with find() has to be a bytes object rather than a string as well, eg. s.find(b'blabla'):
#!/usr/bin/env python3
import mmap
with open('example.txt', 'rb', 0) as file, \
mmap.mmap(file.fileno(), 0, access=mmap.ACCESS_READ) as s:
if s.find(b'blabla') != -1:
print('true')
You could also use regular expressions on mmap e.g., case-insensitive search: if re.search(br'(?i)blabla', s):
As Jeffrey Said, you are not checking the value of check(). In addition, your check() function is not returning anything. Note the difference:
def check():
with open('example.txt') as f:
datafile = f.readlines()
found = False # This isn't really necessary
for line in datafile:
if blabla in line:
# found = True # Not necessary
return True
return False # Because you finished the search without finding
Then you can test the output of check():
if check():
print('True')
else:
print('False')
Here's another way to possibly answer your question using the find function which gives you a literal numerical value of where something truly is
open('file', 'r').read().find('')
in find write the word you want to find
and 'file' stands for your file name
if True:
print "true"
This always happens because True is always True.
You want something like this:
if check():
print "true"
else:
print "false"
Good luck!
I made a little function for this purpose. It searches for a word in the input file and then adds it to the output file.
def searcher(outf, inf, string):
with open(outf, 'a') as f1:
if string in open(inf).read():
f1.write(string)
outf is the output file
inf is the input file
string is of course, the desired string that you wish to find and add to outf.
Your check function should return the found boolean and use that to determine what to print.
def check():
datafile = file('example.txt')
found = False
for line in datafile:
if blabla in line:
found = True
break
return found
found = check()
if found:
print "true"
else:
print "false"
the second block could also be condensed to:
if check():
print "true"
else:
print "false"
Two problems:
Your function does not return anything; a function that does not explicitly return anything returns None (which is falsy)
True is always True - you are not checking the result of your function
.
def check(fname, txt):
with open(fname) as dataf:
return any(txt in line for line in dataf)
if check('example.txt', 'blabla'):
print "true"
else:
print "false"
How to search the text in the file and Returns an file path in which the word is found
(Как искать часть текста в файле и возвращять путь к файлу в котором это слово найдено)
import os
import re
class Searcher:
def __init__(self, path, query):
self.path = path
if self.path[-1] != '/':
self.path += '/'
self.path = self.path.replace('/', '\\')
self.query = query
self.searched = {}
def find(self):
for root, dirs, files in os.walk( self.path ):
for file in files:
if re.match(r'.*?\.txt$', file) is not None:
if root[-1] != '\\':
root += '\\'
f = open(root + file, 'rt')
txt = f.read()
f.close()
count = len( re.findall( self.query, txt ) )
if count > 0:
self.searched[root + file] = count
def getResults(self):
return self.searched
In Main()
# -*- coding: UTF-8 -*-
import sys
from search import Searcher
path = 'c:\\temp\\'
search = 'search string'
if __name__ == '__main__':
if len(sys.argv) == 3:
# создаем объект поисковика и передаем ему аргументы
Search = Searcher(sys.argv[1], sys.argv[2])
else:
Search = Searcher(path, search)
# начать поиск
Search.find()
# получаем результат
results = Search.getResults()
# выводим результат
print 'Found ', len(results), ' files:'
for file, count in results.items():
print 'File: ', file, ' Found entries:' , count
If user wants to search for the word in given text file.
fopen = open('logfile.txt',mode='r+')
fread = fopen.readlines()
x = input("Enter the search string: ")
for line in fread:
if x in line:
print(line)
found = False
def check():
datafile = file('example.txt')
for line in datafile:
if blabla in line:
found = True
break
return found
if check():
print "true"
else:
print "false"
found = False
def check():
datafile = file('example.txt')
for line in datafile:
if "blabla" in line:
found = True
break
return found
if check():
print "found"
else:
print "not found"
Here's another. Takes an absolute file path and a given string and passes it to word_find(), uses readlines() method on the given file within the enumerate() method which gives an iterable count as it traverses line by line, in the end giving you the line with the matching string, plus the given line number. Cheers.
def word_find(file, word):
with open(file, 'r') as target_file:
for num, line in enumerate(target_file.readlines(), 1):
if str(word) in line:
print(f'<Line {num}> {line}')
else:
print(f'> {word} not found.')
if __name__ == '__main__':
file_to_process = '/path/to/file'
string_to_find = input()
word_find(file_to_process, string_to_find)
"found" needs to be created as global variable in the function as "if else" statement is out of the function. You also don't need to use "break" to break the loop code.
The following should work to find out if the text file has desired string.
with open('text_text.txt') as f:
datafile = f.readlines()
def check():
global found
found = False
for line in datafile:
if 'the' in line:
found = True
check()
if found == True:
print("True")
else:
print("False")
so im building a simple decoder tool currently it is able to decode texting short hand expressions, like lol, to its full phrase based off of values stored in a dictionary read in from a txt file. what i would like to do is reverse this process. I would like to take the phrase laugh out loud out of the string and replace it with its abbreviation, lol. I'm new to python so my knowledge is currently limited substantially. I do know a string in immutable so i know to convert the string to a list but my issue is how do i split the string and still keep the laugh out loud together so i can run it agaisnt the dictionary. here is my code minus the txt file any ideas or comments would be greatly appreciated.
class Decry:
def __init__(self):
self.dic_usr = 0
self.decrypted = "none"
self.encrypted = "none"
self.f = 0
self.list1 = []
self.list2 = []
self.list3 = []
self.dict1 = []
self.key1 = []
self.key2 = []
self.key3 = "none"
def __buildDiction__(self):
self.f = open("dict")
self.build_list = self.f.read().splitlines()
self.d_dict = {}
for i in self.build_list:
x = i.split(",")
self.d_dict[x[0]] = x[1]
return self.d_dict
def decoder(self, usr):
self.f = self.__buildDiction__()
self.list1 = usr.split(" ")
for i in self.list1:
if i in self.f:
self.list1[self.list1.index(i)] = self.f[i]
self.decrypted = " ". join(self.list1)
return self.decrypted
def dictionary(self):
self.f = self.__buildDiction__()
self.list2 = []
self.list3 = []
self.dict1 = []
for i in self.f:
self.list3.append(i)
self.list2.append(self.f[i])
for n, g in zip(self.list3, self.list2):
self.dict1.append(n)
self.dict1.append(g)
self.key1 = [self.dict1[i:i+2] for i in range(0, len(self.dict1), 2)]
self.key2 = [" ".join(x) for x in self.key1]
self.key3 = "\n".join(self.key2)
return self.key3
def main():
print("\nWelecome to quick decrypt!!!\n"
" /~~~~~~~~~~~~~~~~~~~~~~/")
print("\n\nUse the number you desire.\n"
"Proceed at your own risk:\n"
" 1. Decrypts\n"
" 2. Read dictionary\n"
" 3. Add definitions to dictionary\n"
" 4. Quit")
deco = Decry()
option = int(input())
if option == 1:
usr_input = str(input("Enter phrase to be decoded:\n"))
f = deco.decoder(usr_input)
print(f, "\n")
return main()
if option == 2:
f = deco.dictionary()
print(f, "\n")
return main()
if option == 3:
with open("dict", "a") as txt1:
txt1.write("\n" + str(input("Enter code followed by definition with a comma no space:\n")))
return main()
if __name__ == "__main__":
main()
my issue is how do i split the string and still keep the laugh out loud together so i can run it against the dictionary
Why split the string at all? Here is a very simple solution that I hope will illustrate an alternative way to solve this without needing to split the string:
phrases = {'lol': 'laugh out loud', 'tbd': 'to be decided', 'btw': 'by the way'}
userString = "by the way here is a simple solution laugh out loud"
for abbr, phrase in phrases.items():
userString = userString.replace(phrase, abbr)
print userString
Produces:
btw here is a simple solution lol
For larger strings you may want to consider looking at regular expressions or other more efficient techniques.
As an exercise you may want to think about how string.replace works - how would you implement that function?