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
Related
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")
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' )
So I am trying to make a game where the 'GameMaster' picks the first word from a .txt file, then the user tries to guess the word. Once the user correctly guess the word, the GameMaster looks to the next line in the file and the user has to guess again, so on and so forth...
The problem I am having, is getting the program to assign variables as the game continues. The program should iteratively look until there are no more words to choose from, whether that be 2 or infinity.
Since I don't have much experience working with file interaction in python, the best example I have is something like this:
file "input.txt" will contain:
dog
cat
bird
rat
mouse
And I am looking at what in in the .txt file with this:
def file_read():
with open ('/Users/someone/Desktop/input.txt', 'r') as myfile:
data = myfile.read()
for line in data:
line.rstrip()
return data
Your function returns the entire contents of the file, unaltered. myfile.read() returns the data from the file as a string. The for loop then iterates over every character in that string, not the lines. Furthermore, rstrip() operates only on each character. It does not affect the contents of data because data is an immutable string and the return value of rstrip() is not stored anywhere.
Something like this would better suit:
def file_read():
with open('/Users/someone/Desktop/input.txt') as myfile:
return [line.rstrip() for line in myfile]
This will return a list of the stripped lines from the file. Your word guessing code would then iterate over the list.
The above will work, however, it is not very efficient if the input file is large because all of the file would be read into memory to construct the list. A better way is to use a generator which yields a stripped line one at a time:
def file_read():
with open('/Users/someone/Desktop/input.txt') as myfile:
for line in myfile:
yield line.rstrip()
Now that function is so simple, it seems pointless to bother with it. Your code could simply be:
with open('/Users/someone/Desktop/input.txt') as myfile:
for line in myfile:
user_guess_word(line.rstrip())
where user_guess_word() is a function that interacts with the user to guess what the word is, and returns once the guess it correct.
This way uses readlines to get file contents in a list line by line. readlines returns a list containing lines.
Now iterate through list to check if user input matches with line content (which is a word in this case).
with open ('/Users/someone/Desktop/input.txt', 'r') as myfile:
words = myfile.readlines()
while x < len(words):
if words[x] == input('Enter word to guess'):
print('Predicted word correctly')
else:
print('Wrong word. Try again')
x -= 1
x += 1
You can do it like,
def fun():
data = open('filename', 'r').readlines()
user_guess, i = None, 0
while i < len(data):
user_guess = input()
if user_guess not None and user_guess == data[i]:
i = i + 1
Please trim() / strip() also while you compare user_guess and data[i]
I was just wondering if I can make a simple script that searches for different strings on user input. Let's say I want to search first time for word "apple" and the second time "orange" and to display all the lines where apples and oranges exist. I want first to be indipendent from the second search.
`string = "start"
while string != "end":
string = input('Enter fruit: ')
print("looking for ",string )
for line in f:
if "Started" and string in line:
print("debug")
print(line)`
What this does is works first time and doesn't the second time. I am prompted after the output to enter another fruit but instead of presenting all the lines where the fruit is found it just prompts with another request to enter a fruit.
Assuming you have some line like f = open('BigTextFileFullOfFruit.txt', 'r') above the snippet you posted:
You can only iterate once over a file. You have to call f.seek(0) to go over it again.
This is because f is an iterator and it cannot be consumed more than once. After that it is exhausted and will not yield anymore.
To go around this, you may seek to the beginning to re-iterate or save the contents in a list for reuse.
# Put this inside your outermost loop
string = raw_input("Enter string: ")
f = fp.readline()
while f:
if f.find(string) >= 0 and "Started":
print(f, end=' ')
f = fp.readline()
I need assistance for this problem I'm having. I'm trying to get my program to grab the first Letter from the first Word on every single line and print them in a single string.
For example if I type the following words in a block of text:
People like to eat pie for three reasons, it tastes delicious. The taste is unbelievable, next pie makes a
great dessert after dinner, finally pie is disgusting.
The result should be "Pg" this is a small example but you get the idea.
I started on the code but I'm clueless on where to go.
#Prompt the user to enter a block of text.
done = False
print("Enter as much text as you like. Type EOF on a separate line to finish.")
textInput = ""
while(done == False):
nextInput= input()
if nextInput== "EOF":
break
else:
textInput += nextInput
#Prompt the user to select an option from the Text Analyzer Menu.
print("Welcome to the Text Analyzer Menu! Select an option by typing a number"
"\n1. shortest word"
"\n2. longest word"
"\n3. most common word"
"\n4. left-column secret message!"
"\n5. fifth-words secret message!"
"\n6. word count"
"\n7. quit")
#Set option to 0.
option = 0
#Use the 'while' to keep looping until the user types in Option 7.
while option !=7:
option = int(input())
#I have trouble here on this section of the code.
#If the user selects Option 4, extract the first letter of the first word
#on each line and merge into s single string.
elif option == 4:
firstLetter = {}
for i in textInput.split():
if i < 1:
print(firstLetter)
You can store the inputs as a list, then get the first character from each list:
textInput = []
while(done == False):
nextInput= input()
if nextInput== "EOF":
break
else:
textInput.append(nextInput)
...
print ''.join(l[0] for l in textInput)
I'd start by making a list of lines instead of a single string:
print("Enter as much text as you like. Type EOF on a separate line to finish.")
lines = []
while True:
line = input()
if line == "EOF":
break
else:
lines.append(line)
Then, you can get the first letters with a loop:
letters = []
for line in lines:
first_letter = line[0]
letters.append(first_letter)
print(''.join(letters))
Or more concisely:
print(''.join([line[0] for line in lines]))
This is very simple:
with open('path/to/file') as infile:
firsts = []
for line in infile:
firsts.append(line.lstrip()[0])
print ''.join(firsts)
Of course, you could do the same thing with the following two-liner:
with open('path/to/file') as infile:
print ''.join(line.lstrip()[0] for line in infile)
Hope this helps