I'm completely new to Python and coding in general. I am needing to write a code that allows the user to input many lines and when they are finished writing their multiple sentences, they enter a single period to stop the program and the program will then tell the user how many words were inputted. How would I go about doing this?
Here is what I have so far:
print("Enter as many lines of text as you want.")
print("When you're done, enter a single period on a line by itself.")
while True:
print("> ", end="")
line = input()
if line == ".":
break
totalWords = line.split()
newWords = totalWords.append(line)
wordCount = len(newWords)
print("The number of words entered:" , wordCount, "")
You should set content out of loop.
content = []
while True:
line = input()
if line == ".":
break
words = line.split()
content.append(words)
words_list = [item for sublist in content for item in sublist]
print(len(words_list))
Besides, Most functions that change the items of sequence/mapping does return None. So newWords = totalWords.append(line) will always return None.
Related
Here's my code:
wordlist = open('words.txt')
word = input()
i = 0
def loop():
for i in range(466549):
if wordlist.readline().strip() == word:
print(f'found in {i}')
return
else:
print(f"not {wordlist.readline()}")
i = i + 1
loop()
Not only does it not return the first value of the list, but it also doesn't say that it found my word when it did. I got my words.txt file from GitHub, and the second word is "1080". But when I put that in, it prints 'not 1080' even though it clearly is.
I think what you are looking for is:
word = input("enter word: ").strip()
def loop():
with open("words.txt") as f:
wordList = f.readlines()
for i,line in enumerate(wordList):
line = line.strip()
if line == word:
print(f"found in line {i}")
return
else:
print(f"did not find in {line}")
loop()
or if you want to stick to using just readline:
word = input("enter word: ").strip()
wordList = open("words.txt")
def loop():
for i in range(466549):
line = wordList.readline().strip()
if line == word:
print(f"found in line {i}")
return
else:
print(f"did not find in {line}")
loop()
wordList.close()
Maybe you wanna find if specific word in text file.
First, wordlist.readline() actually reads a line from file which means it is not reproducible. so, print(f"not {wordlist.readline()}") doesn't work as you expected.
For example, let's say words.txt looks like below.
hello
1080
world
When you read first line with if wordlist.readline() ... inside loop, that value is "hello", and this is not 1080, so else statement runs. At here, you reads a line with print(f"not {wordlist.readline()}") as second which is 1080, thus not 1080 gonna be printed.
And finally, if wordlist.readline() ... will read world from file, this is also not 1080, and next readline() will be None.
Secondary problem is that variable i is not utilized properly. i is incremented automatically thanks to range and for keyword (Strictly, it just next value from iterable object, not increment), so you don't need like i = 0 or i = i + 1
Third thing is derived from the problem pointed in first one, which is None.strip() is impossible so it will raise an exception.
There are more things to say, but I'll just show you my example so you can compare it with yours
input_wordlist = open('words.txt')
input_word = input()
def loop(word, wordlist):
for index, line in enumerate(wordlist.readlines()):
if line.strip() == word:
# or if you wanna know whether word is in line
# if word in line:
print(f"found in {index}")
return
else:
print(f"not in {line}")
loop(input_word, input_wordlist)
input_wordlist.close()
I want to print if the word appears, as well as how many times the word appears in the file. I can't get it to say anything other than this word appears 1 or 0 times in the file.
This problem occurs on line 26, print("It appears " + str(wordcount[word]) + " times")
specifically str(wordcount[word]). This probably simple question, but this is my first week of python so if anyone has an idea please share. Thanks!
I've tried putting wordcount[word], word_counter.__getitem__(wordcount[word]), and word_counter.__getitem__(wordcount)
import collections
file = open(r"C:\Users\Patrick Wu\Documents\1wordfreqtest.txt", "r")
if file.mode == "r":
contents = file.read()
word = input("Word to check for :")
wordcount = {}
"""this below is to remove difference between upper and lower cases as
well as punctuation"""
for word in contents.lower().split():
word = word.replace(".","")
word = word.replace(",","")
word = word.replace(":","")
word = word.replace("\"","")
word = word.replace("!","")
word = word.replace("“","")
word = word.replace("‘","")
word = word.replace("*","")
if word not in wordcount:
wordcount[word] = 1
else:
wordcount[word] += 1
word_counter = collections.Counter(wordcount)
if word in str(contents):
print("This word is in the file :)")
print("It appears " + str(wordcount[word]) + " times")
else:
print("This word isn't in the file")
The variable word is overwritten in the local scope, by the loop. So your input word is overwritten by the loop and you end up checking the count of the last word of the input file. Change the input word to be a different variable name than the word you're iterating through in the file.
You have a scoping problem, by using the same name "word" both in the input and in the for-loop.
I would suggest doing something like this:
word = input("Word to check for :")
with open('your_file.txt') as f:
raw = f.read()
num_appearences = raw.count(word)
print(f"The word {word} appears {num_appearences} times in the file")
You can use this code:
import collections
file = open("wordfreqtest.txt", "r")
if file.mode == "r":
contents = file.read().lower()
word = input("Word to check for :").lower()
times = 0
finish = 0
while finish==0:
if word in contents:
contents = contents[contents.find(word) + len(word):]
times += 1
else:
break
if times > 0:
print("This word is in the file :)")
print("It appears " + str(times) + " times")
else:
print("This word isn't in the file")
I have to count the number of times a given word appears in a given text file, this one being the Gettysburg Address. For some reason, it is not counting my input of 'nation' so the output looks as such:
'nation' is found 0 times in the file gettysburg.txt
Here is the code I have currently, could someone point out what I am doing incorrectly?
fname = input("Enter a file name to process:")
find = input("Enter a word to search for:")
text = open(fname, 'r').read()
def processone():
if text is not None:
words = text.lower().split()
return words
else:
return None
def count_word(tokens, token):
count = 0
for element in tokens:
word = element.replace(",", " ")
word = word.replace("."," ")
if word == token:
count += 1
return count
words = processone()
word = find
frequency = count_word(words, word)
print("'"+find+"'", "is found", str(frequency), "times in the file", fname)
My first function splits the file into a string and turns all letters in it lower case. The second one removes the punctuation and is supposed to count the word given in the input.
Taking my first coding class, if you see more flaws in my coding or improvements that could be made, as well as helping find the solution to my problem, feel free.
In the for loop in the count_word() function, you have a return statement at the end of the loop, which exits the function immediately, after only one loop iteration.
You probably want to move the return statement to be outside of the for loop.
as a starter I would suggest you to use print statements and see what variables are printing, that helps to breakdown the problem. For example, print word was showing only first word from the file, which would have explained the problem in your code.
def count_word(tokens, token):
count = 0
for element in tokens:
word = element.replace(",", " ")
word = word.replace("."," ")
print (word)
if word == token:
count += 1
return count
Enter a file name to process:gettysburg.txt
Enter a word to search for:nation
fourscore
'nation' is found 0 times in the file gettysburg.txt
Use code below:
fname = input("Enter a file name to process:")
find = input("Enter a word to search for:")
text = open(fname, 'r').read()
def processone():
if text is not None:
words = text.lower().split()
return words
else:
return None
def count_word(tokens, token):
count = 0
for element in tokens:
word = element.replace(",", " ")
word = word.replace("."," ")
if word == token:
count += 1
return count
words = processone()
word = find
frequency = count_word(words, word)
print("'"+find+"'", "is found", str(frequency), "times in the file", fname)
statement "return" go out statement "for"
This code is meant to pick an artist from internal file (text file), read it and pick randomly from the internal file the artist (that are in the text file in array style, e.g., "carrot apple banana"), therefore I added .txt to the chosen artist so the program will open artist's file with songs and pick a random song.
import random
loop = False
counter = 0
points = 0
max_level = 10
while loop == False:
for lines in open("pick.txt").readlines():
art = lines.split()
artist = random.choice(art)
for i in open((artist) + ".txt"):
song = i.split()
song_name = random.choice(song)
print("the song begins with :" , song_name , "this song is by :" , artist)
answer = input("Enter full name of the song : ")
if answer == song_name:
points = points +3
print("correct")
counter = counter +1
print(counter)
elif answer != song_name:
print("WRONG !!! \n try again")
dec = input("Please enter the full name of the song :")
if dec == song_name:
points = points +2
print("correct")
counter = counter +1
print(counter)
elif dec != song_name:
print("smh \n WRONG")
counter = counter +1
print(counter)
elif counter >= max_level:
print("The End")
quit()
else:
print("error")
input()
Afterwards when I run the code in python shell, there is a random chance that I get this error, either straight away or later on:
raise IndexError('Cannot choose from an empty sequence') from None
IndexError: Cannot choose from an empty sequence
That error is from the random module by the looks of it. This is probably when you’re reading the file and there is a line that is blank.
A cause is usually the last line of the file which is often a blank newline/EOF.
Just add a check when reading your file(s):
for line in open(artist + '.txt', 'r'):
if line.strip():
song = line.strip().split()
song_name = random.choice(song)
An empty line will have a ‘truthiness’ value of 0 or False so a line with content returnsTrue.
Your error probably arises from an empty line in one of your text-files.
I was able to duplicate your error with your exact code and the following text-files:
pick.txt with only the word adele,
and adele.txt with hello-from-the-other-side and two new lines.
You can test this in prelude:
>>> for i in open("adele.txt"):
... song = i.split()
...
>>> song
[]
On another note, you seem to be iterating throughout the lines in a textfile before you do anything with the data in the lines. That can't possibly make sense. I would advice you to add things in a list as you go, and then select from this list instead.
In the beginning of my program, i opened a file with f = open("foods.txt", "r+"). Later I called this method i created
def findFood(food):
foodRegex = re.compile(r'(?P<food>\S+)\s+\-.*')
for line in f.readlines():
print line
duplicateFound = re.search(foodRegex, line)
if duplicateFound.group('food') == food:
return duplicateFound
else:
return False
However I run the method again. But my program doesn't work the way I want it to. Specifically
def build_meal_plan():
number_of_items = int(raw_input("How many items would you like to add to your meal plan? "))
count = 0
while number_of_items > 0:
print count
food = raw_input("Enter in food name: ")
print food
if findFood(food):
servings = int(raw_input("Number of servings: "))
else:
print "Food not found! Try again? (y/n): ",
choice = raw_input()
if choice == 'y' or choice == "yes":
number_of_items += 1
else:
return
However during the 2nd run of my findFood method I cannot locate an item i know exists within the .txt file. I am not sure why I cannot find the same item I found in the text file during the first run. My assumption is that you can only go through a txt file once.
Once you call f.readlines(), you are at the end of the file. To return to the start, so you can go through it again, call f.seek(0):
def findFood(food):
foodRegex = re.compile(r'(?P<food>\S+)\s+\-.*')
for line in f.readlines():
...
f.seek(0)
Alternatively, you can import the contents of the file to a list:
def import_file(filename):
with open(filename) as f:
content = [line.strip() for line in f]
return content
And use that instead of referring back to the file.
def findFood(food, data):
foodRegex = re.compile(r'(?P<food>\S+)\s+\-.*')
for line in data:
...
Then you don't need to worry about returning to the start.