unable to read what is the written words using python - python

If i manually key the words in the txt and run the program the "word found" can be displayed but when i run python for the new words it shows up in the text file but it does not display "word found" when i run it for a second time. Any idea for this?
word = input("Please enter a word: " ).lower()
dictionary = open("Dictionary.txt","r")
if word in dictionary:
print("word found")
else:
dictionary = open("Dictionary.txt","a")
dictionary.write(word)
dictionary.write("\nThis sentence contains" + " " + word)
dictionary.close()

You have a few things you need to be careful of. I made an assumption to get a working example that the words are stored on individual lines. I also read them in and remove and leading or trailing whitespace so the match can work
word = input("Please enter a word: ").lower()
dictionary = open("Dictionary.txt", "r")
words = [x.strip() for x in dictionary.readlines()]
if word in words:
print("word found")
else:
appending_handle = open("Dictionary.txt", "a")
appending_handle.write("\n" + word)
appending_handle.close()
dictionary.close()
I also made a new variable to store the second dictionary open. Otherwise you will never close the original because you've lost the reference.
It's also not clear you want to do this at all
dictionary.write("\nThis sentence contains" + " " + word)
since it adds these to the dictionary

Try using:
if word in dictionary == True:
print("Word found")

Related

Reading line in a file that has been purposely changed

So let's say I have something like;
def scramble():
word = open("wordlist.txt", "a")
userword = input("Give me a word to scramble")
newword = userword.replace("a", "*")
newword2 = neword.replace("o", "0")
word.write(userword)
word.write(\n)
word.close
Take a word, replace characters with those in the code and append that to a file. How can I then create a different function where I ask the user to enter that word again, the code goes back to that file, almost "decrypts" the word and spits it back out at the user in the most simplest of terms. I don't care how messy I'm just completely lost.
I've attempted to reverse the scrambled word but every time I go to check the file for it, regardless of whether or not the word is in there it fails the check.
def unscramble():
word = open("wordlist.txt", "r")
userinput = input("Enter a word and I'll see if i have it")
userinput2 = userinput.replace("*","a")
userinput3 = userinput2.replace("0","o")
for line in word:
if userinput3 in line:
print("Yes, I do have that word. Would you like to see it scrambled?")
else:
print("Sorry, I don't have that")

Calculating how many times sentence words are repeating in the file

I want to check how many times a word is repeating in the file. I have seen other codes on finding words in file but they won't solve my problem.From this I mean if I want to find "Python is my favourite language"The program will split the text will tell how many times it has repeated in the file.
def search_tand_export():
file = open("mine.txt")
#targetlist = list()
#targetList = [line.rstrip() for line in open("mine.txt")]
contentlist = file.read().split(" ")
string=input("search box").split(" ")
print(string)
fre={}
outputfile=open("outputfile.txt",'w')
for word in contentlist:
print(word)
for i in string:
# print(i)
if i == word:
print(f"'{string}' is in text file ")
outputfile.write(word)
print(word)
spl=tuple(string.split())
for j in range(0,len(contentist)):
if spl in contentlist:
fre[spl]+=1
else:
fre[spl]=1
sor_list=sorted(fre.items(),key =lambda x:x[1])
for x,y in sor_list:
print(f"Word\tFrequency")
print(f"{x}\t{y}")
else:
continue
print(f"The word or collection of word is not present")
search_tand_export()
I don't quite understand what you're trying to do.
But I suppose you are trying to find how many times every word from a given sentence is repeated in the file.
If this is the case, you can try something like this:
sentence = "Python is my favorite programming language"
words = sentence.split()
with open("file.txt") as fp:
file_data = fp.read()
for word in words:
print(f"{file_data.count(word)} occurence(s) of '{word}' found")
Note that the code above is case-sensitive (that is, "Python" and "python" are different words). To make it case-insensitive, you can bring file_data and every word during comparison to lowercase using str.lower().
sentence = "Python is my favorite programming language"
words = sentence.split()
with open("file.txt") as fp:
file_data = fp.read().lower()
for word in words:
print(f"{file_data.count(word.lower())} occurence(s) of '{word}' found")
A couple of things to note:
You are opening a file and even don't close it finally (although you should). It's better to use with open(...) as ... (context-manager), so the file is closed automatically.
Python strings (as well as lists, tuples etc.) have .count(what) method. It returns how many occurences of what are found in the object.
Read about PEP-8 coding style and give better names to variables. For example, it is not easy to understand what does fre means in your code. But if you name it as frequency, the code will become more readable, and it will be easier to work with it.
to be continued
Try this script. It finds word in file and counts how many times it is found in words:
file = open('hello.txt','r')
word = 'Python'
words = 0
for line in file:
for word in line:
words += 1
print('File contains ' + word + ' ' + str(words) + ' times' )

Python Function that prints the number of words in a txt file and prints the first 10 words

My code:
So far I've managed to print the whole text file in list format. However, I am now trying to get it to print the number of words along with the first 10 words in the file.
T
This code will print the amount of words in the file, and the first ten words (if the file is not ten words long, it will print as many as it can):
def get_dictionary_wordlist():
return open('dictionary.txt','r').read()
def test_get_dictionary_wordlist():
text = get_dictionary_wordlist()
textlist = text.split(" ")
print("No. of Words: " + str(len(textlist)))
try:
for word in range(0,10):
print(textlist[word])
except:
pass
test_get_dictionary_wordlist()
for i in range(N):
f.readline()

Reading a word from a file in a specific way

So I am trying to store a single word to a file (which i have already managed to figure out how to do). The program would then repeat and ask me to input another word. It should check if this word already exists in the file (which it should). I have it to the point where i have inputted a word and it has stored it in the file but when i input the same word again it doesn't realise that the word already exists in the file. (This is all in a def function so when i say the next time it goes round i mean the next time i call the function)
Here is the code:
def define():
testedWord = subject
lineNumber = 1
lineInFile = "empty"
exists = False
while lineInFile != "":
wordsFile = open("Words.txt", "a")
lineInFile = linecache.getline("Words.txt", lineNumber)
lineNumber = lineNumber + 1
lineInFile = lineInFile.replace("\n", "")
if lineInFile == subject:
definitionNumber = lineNumber
exists = True
if exists == False:
wordsFile.write(testedWord)
wordsFile.write("\n")
wordsFile.close()
subject = input("")
define()
##This whole thing basically gets repeated
Like i said, if i store a new word and then in the same program try and put in the same word again then it won't recognize that it has already stored this word. When i stop the program and restart it, it works (but i dont want to have to do that)
Thanks for you help (if it is possible to help lol)
Dan
I think you're making (almost) everything more complicated than it needs to be. Here is a different way of doing what you're trying to do:
def word_check(f_name, word):
with open(f_name) as fi:
for line in fi: # let Python deal with line iteration for you
if line.startswith(word):
return # return if the word exists
# word didn't exist, so reopen the file in append mode
with open(f_name, 'a') as fo:
fo.write("{}\n".format(word))
return
def main():
f_name = "test.txt"
with open(f_name, 'w') as fo:
pass # just to create the empty file
word_list = ['a', 'few', 'words', 'with', 'one',
'word', 'repeated', 'few'] # note that 'few' appears twice
for word in word_list:
word_check(f_name, word)
if __name__ == "__main__":
main()
This produces an output file with the following text:
a
few
words
with
one
repeated
In this example, I just created a list of words instead of using input to keep the example simple. Note how inefficient your current method is, though. You're reopening a file and reading every line for every word entered. Consider building your word list in memory instead, and writing it out at the end. Here's an implementation that takes advantage of the built-in set datatype. They don't allow repeated elements. If you're okay with writing out the file at the end of the program run instead of on-the-fly, you can do this instead:
def main():
word_set = set()
while True:
word = input("Please enter a word: ")
if word == 'stop': # we're using the word 'stop' to break from the loop
break # this of course means that 'stop' should be entered
# as an input word unless you want to exit
word_set.add(word)
with open('test.txt', 'w') as of:
of.writelines("{}\n".format(word) for word in word_set)
# google "generator expressions" if the previous line doesn't
# make sense to you
return
if __name__ == "__main__":
main()
Printed output:
Please enter a word: apple
Please enter a word: grape
Please enter a word: cherry
Please enter a word: grape
Please enter a word: banana
Please enter a word: stop
Produces this file:
grape
banana
cherry
apple

encrypting a file using shift

Not sure what im doing wrong here? the program asks for file name and reads the file but when it come to printing the encoded message it comes up blank. What am I missing, as if I change the phrase to just normal raw_input("enter message") the code will work, but this is not reading from the txt file.
letters = "a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z"]
cshift = int(input("Enter a number: "))
phrase = open(raw_input("file name: "), 'r')
newPhrase = ""
for l in phrase:
if l in letters:
pos = letters.index(l) + cshift
if pos > 25:
pos = pos-26
newPhrase += letters[pos]
else:
newPhrase += " "
print(newPhrase)
The problem here is that the for-loop on this line:
for l in phrase:
will return complete lines, not individual characters.
As such you will have to loop through individual characters from those lines as well, or read the file binary, or use functions on the file object that will read one character at a time.
You could simply do this:
for line in phrase:
for l in line:
... rest of your code here
The open function does not return a string, but a handle to the opened file from which strings can be read. You should search for information on how to read a file into a string in Python and then try it in a REPL to make sure it returns a string and not something else.

Categories

Resources