This is from Think Python. Trying to go through each line(One word in each line) of a file and only printing out every word that does not contain the letter e.
I've spend like 4 hours trying different ways to filter the file through my function, but i give in. It seems it that it only filter out the first e it finds in a word: if a word has two e's than it prints it out anyways.
def has_no_e():
file_name = raw_input('Enter the full path and file name: ')
fin = open(file_name)
line = fin.readline()
for line in fin:
word = line.strip()
print word
for letter in word:
if letter == 'e':
continue
print word
has_no_e()
My code is indented btw, i think it messes up when i ctrl + v
If there's a way to make it my code shorter please let me know :]
with open(filename) as f:
for line in f:
if not 'e' in line: print line.strip()
Some comments:
use with when working with files, although it's a newer construct in python, it helps you to manage your files (i.e. closing it again when not needed anymore)
word = line.strip() makes your code not very readable. Use line = line.strip() (you will only use either line or word, not both, I assume)
So why was your code not working?
for letter in word:
if letter == 'e':
continue
print word
Here you split the word into its letters, then you check if the letter is equal to e. If that's not the case, you print the word, otherwise you jump to the next letter. So you print the word as many times as there are letters different from 'e'.
A way to solve this would be to define a boolean, which tells you if there was an e in the word:
hasE = False
for letter in word:
if letter == 'e':
hasE = True
break
if not hasE: print word
Note that Python also has a fancy way to solve problems like this:
for letter in word:
if letter == 'e': break
else:
print word
It looks like pfnuesel went over the main reason the code wasn't working when he wrote:
"Here you split the word into its letters, then you check if the
letter is equal to e. If that's not the case, you print the word,
otherwise you jump to the next letter. So you print the word as many
times as there are letters different from 'e'."
Here's the way I solved exercise 9.2 in Think Python:
def has_no_e(word):
return "e" not in word
fin = open('words.txt')
for line in fin:
word = line.strip()
if has_no_e(word):
print word
Related
a_file = open(r"C:\Users\lisin\Desktop\Code\Bomb Party\wordlist.txt", "r")
list_of_lists = []
for line in a_file:
stripped_line = line.strip()
line_list = stripped_line.split()
list_of_lists.append(line_list)
a_file.close()
wordlist = list_of_lists
contains = input("? ")
matches = [match for match in wordlist if str(contains) in match]
print(matches)
When I run the code and put any letters in, it returns nothing. The wordlist has it, but it is still not returning anything. I'm trying to get any word that contains what you input.
Edit: I was not very clear of want I wanted to create. want to be able to input a string, lets say "ee", and have it return any words that have "ee" in them, like "bee" or "free"
Fixed! It turns out it was making a list of lists and I did not realize that somehow. So I just converted the list into a string and then separated it into a list
def Convert(string):
li = list(string.split(" "))
return li
with a_file as myfile:
x = myfile.read().replace('\n', ' ')
Sorry if I wasn't clear about what I wanted. Thanks anyway
Your problem is how you fill matches. match is a list of string and not a string itself, this is why the condition is never fulfilled.
I assumed you wanted every occurrences of contains in wordlist. To resolve this, you want a list of coordinates as (line, word). If I write it like you with tuple of int:
matches = [(index_line, index_word) for index_line, line_list in enumerate(wordlist) for index_word, word in enumerate(line_list) if word == contains]
I think it's hard to read. I recommend this instead:
matches = []
for index_line, line_list in enumerate(wordlist):
for index_word, word in enumerate(line_list):
if word == contains:
matches.append((index_line, index_word))
print("Occurence(s) of the word can be found at :")
for match in matches:
print(f" Line {match[0]}, word {match[1]}")
You may also use a function:
def matches(wordlist : list, contains : str) -> list:
for index_line, line_list in enumerate(wordlist):
for index_word, word in enumerate(line_list):
if word == contains:
yield (index_line, index_word)
print("Occurence(s) of the word can be found at :")
for match in matches(wordlist, contains):
print(f" Line {match[0]}, word {match[1]}")
enumerate() return two variables : the index of the element in the list, and the element itself. yield is harder to understand, it let you read the answer to this question.
Input :
Hello !
My name is John
And you ?
John too !
contains = "John"
Output :
Occurence(s) of the word can be found at :
Line 2, word 4
Line 4, word 1
I'm currently stuck on a problem where I have to find all palingrams in a list. I made one piece of code, however it was not efficient at all and took around 3 and a half hours to finish. I needed to find something that is more time effect.
Right now I am currently stuck with this chunk of code:
import sys
def load(file):
"""Open a text file & turn contents into a list of lowercase strings."""
try:
with open(file) as in_file:
loaded_txt = in_file.read().strip().split('\n')
loaded_txt = [x.lower() for x in loaded_txt]
return loaded_txt
except IOError as e:
print("{}\nError opening {}. Terminating program.".format(e, file),
file=sys.stderr)
sys.exit(1)
def find_palingrams():
pali_list = []
for word in word_list:
if end > 1:
for i in range(end):
if word[i:] == rev_word[:end-i] and rev_word[end-i:] in word_list:
pali_list.append((word, rev_word[end-i:]))
if word[i:] == rev_word[end-i:] and rev_word[:end-i] in word_list:
pali_list.append((rev_word[end-i:], word))
return sorted(pali_list)
I'm having issues with this because it does not print specific outputs that I am looking for. It is printing words, but it is excluding cases such as "aa aa", "a ba", "a baba" etc. There is something that I am not seeing that is causing single letters to not be included fully. I am aware of the end > 1, however even with an attempt to change that I am met with confusion.
Could anyone shed some light?
I guess you mean Palindrome words.
An easier way to check if a word is palindrome:
>>> word = "level"
>>> word == word[::-1]
True
You may wanna use that cleaner way, and then add the word based on the test result:
if word == word[::-1]:
# add it to the list
The target was to bring in a certain str inputs, which have same letters for different words.While I have narrowed down the accuracy percentage. I'm unable to figure out a few problems.
Link to file : http://www.gutenberg.org/files/3201/files/
fln=open('CROSSWD.TXT')
def uses_only(allow,word1,count,count_2):
y=0 #I've tried assigning line before loop as line=fln.readlines() does'nt work
for line in fln:
word=line.strip() # somehow the line is stripped of white spaces here or there
for letter in line: # Does'nt work for in word
x=count
z=count_2
if letter in allow:
count+=1
elif letter not in allow: # break loop for unwanted letters
count=0
count_2+=1
break
if x==len(word) and len(allow)==len(word): # runs if the letters match
y+=x/len(word)
word1+=word+','
return True,word1,int(y) #returns matching words & word count
def run():
allow=input('Enter the only letters the word must contain : ') # input from user
word1=''
count=0
count_2=0
print(uses_only(allow,word1,count,count_2))
run()
The main problem i'm facing is in
for letter in line:
If I use
for letter in word: **# What's making the loop to break?**
it return an empty string, While they're supposed to do the same thing a little concised in the
word=line.strip()
Also kindly help me to bring the match to be more accurate
Input : eat
current output :
(True, 'ate,eat,eta,tae,tat,tea,tee,', 7)
The output gives the words with matching str taken as input for same length & the No. of words that match.
Debugging the code I realized that the error is in the fact that using 'word' the variables x and z are not updated in the last loop, just put them at the end of the for loop:
for letter in word: # Now work for in word
if letter in allow:
count+=1
elif letter not in allow: # break loop for unwanted letters
count=0
count_2+=1
break
x=count
z=count_2
In order to overcome this problem I took the for letter in word into a separate function. This solves both the iteration problem & the accuracy of the string match.
fln=open('CROSSWD.TXT')
def test_word(word,allow): # Test for a sinlgle word in a line
for letter in word:
if letter not in allow:
return False
return True
def use_only():
count=0
allow=input('Enter the letters: ')
word1=''
for line in fln: # iteration for no. of loops
word=line.strip()
if test_word(word,allow)==True: #verify the match
word1+=word+','
count+=1
return word1, count
use_only()
In : letter
Out : ('eel,el,ell,er,ere,err,et,lee,leer,leet,let,letter,letterer,re,ree,reel,reeler,relet,reletter,ret,rete,retell,tee,teeter,tele,tell,teller,terete,terret,tetter,tree,tret,', 32)
I have a program that counts and prints all words in a sentence that contains a specific character(ignoring case).
Code in Python -
item=input()
ip=input().tolower()
r=ip.count(item)
print(r)
ip=ip.split()
for word in ip:
if item in word:
print((word), end=' ')
This program works as expected but for the last word that is printed I don't want a white-space after it.
If anyone could guide me on how to remove the space it would be appreciated.
Why don't you use list comprehension and str.join?
print(' '.join([w for w in ip if item in w]))
I don't think there's a way to remove that, as it's a part of your terminal. Best answer I can give you.
I expanded on the code though, cause I was kinda bored.
sentence = input("Enter a sentence: ").lower()
pull = input("Which character(s) do you want to count?: ").lower()
for c in pull:
occurrences = 0
for character in sentence:
if c == character:
occurrences+=1
if c!=" ": print("\'%s\' appears %d times"%(c, occurrences))
for word in sentence.split():
occurrences = 0
for character in word:
if c == character:
occurrences+=1
if occurrences == 1:
print(("1 time in \'%s\'")%(word))
elif occurrences > 0:
print(("%d times in \'%s\'")%(occurrences,word))
+The solution with a list comprehension appears more concise, but if you prefer an alternative you can use the following. It was tested and worked with the example in the picture.
# Amended solution. The commented lines are the amendment.
item = input('Letter: ')
ip = input('Input: ').lower()
r = ip.count(item)
print(r)
ip = ip.split()
outputString = '' # Added: Initialise an empty string to keep the answer
for word in ip:
if item in word:
outputString += word + ' ' # Changed: Accumulates the answer in a string
print(outputString[:-1]) # Added: Prints all the string's characters
# except the last one, which is the additional space
You're close, just change your print statement from print((word), end=' ') to print((word), end=''). Your print statement has a whitespace for the end but you don't want the whitespace so make the end an empty string.
I want to make a jumble game in python that uses words from a text file rather than from words written directly into the python file(in this case the code works perfectly). But when I want to import them, I get this list:
[['amazement', ' awe', ' bombshell', ' curiosity', ' incredulity', '\r\n'], ['godsend', ' marvel', ' portent', ' prodigy', ' revelation', '\r\n'], ['stupefaction', ' unforeseen', ' wonder', ' shock', ' rarity', '\r\n'], ['miracle', ' abruptness', ' astonishment\r\n']]
I want words to be sorted in one single list, for example:
["amazement", "awe", "bombshell"...]
This is my python code:
import random
#Welcome the player
print("""
Welcome to Word Jumble.
Unscramble the letters to make a word.
""")
filename = "words/amazement_words.txt"
lst = []
with open(filename) as afile:
for i in afile:
i=i.split(",")
lst.append(i)
print(lst)
word = random.choice(lst)
theWord = word
jumble = ""
while(len(word)>0):
position = random.randrange(len(word))
jumble+=word[position]
word=word[:position]+word[position+1:]
print("The jumble word is: {}".format(jumble))
#Getting player's guess
guess = input("Enter your guess: ")
#congratulate the player
if(guess==theWord):
print("Congratulations! You guessed it")
else:
print ("Sorry, wrong guess.")
input("Thanks for playing. Press the enter key to exit.")
I have a text file with words:
amazement, awe, bombshell, curiosity, incredulity,
godsend, marvel, portent, prodigy, revelation,
stupefaction, unforeseen, wonder, shock, rarity,
miracle, abruptness, astonishment
Thank you for help and any suggestions!
quasi one-liner does it:
with open("list_of_words.txt") as f:
the_list = sorted(word.strip(",") for line in f for word in line.split())
print(the_list)
use a double for in a gen-comprehension
splitting against spaces is the trick: it gets rid of the line-termination chars and multiple spaces. Then, just get rid of the commas using strip().
Apply sorted on the resulting generator comprehension
result:
['abruptness', 'amazement', 'astonishment', 'awe', 'bombshell', 'curiosity', 'godsend', 'incredulity', 'marvel', 'miracle', 'portent', 'prodigy', 'rarity', 'revelation', 'shock', 'stupefaction', 'unforeseen', 'wonder']
Only drawback of this quick method is that if 2 words are only separated by a comma, it will issue the 2 words as-is.
In that latter case, just add a for in the gencomp like this to perform a split according to comma and drop the empty result string (if word):
with open("list_of_words.txt") as f:
the_list = sorted(word for line in f for word_commas in line.split() for word in word_commas.split(",") if word)
print(the_list)
or in that latter case, maybe using regex split is better (we need to discard empty strings as well). Split expression being blank(s) or comma.
import re
with open("list_of_words.txt") as f:
the_list = sorted(word for line in f for word in re.split(r"\s+|,",line) if word)
use
lst.extend(i)
instead of
lst.append(i)
split return a list and you append a list to list everytime. Using extend instead will solve your problem.
Please try the following code:
import random
#Welcome the player
print("""
Welcome to Word Jumble.
Unscramble the letters to make a word.
""")
name = " My name "
filename = "words/amazement_words.txt"
lst = []
file = open(filename, 'r')
data = file.readlines()
another_lst = []
for line in data:
lst.append(line.strip().split(','))
print(lst)
for line in lst:
for li in line:
another_lst.append(li.strip())
print()
print()
print(another_lst)
word = random.choice(lst)
theWord = word
jumble = ""
while(len(word)>0):
position = random.randrange(len(word))
jumble+=word[position]
word=word[:position]+word[position+1:]
print("The jumble word is: {}".format(jumble))
#Getting player's guess
guess = input("Enter your guess: ")
#congratulate the player
if(guess==theWord):
print("Congratulations! You guessed it")
else:
print ("Sorry, wrong guess.")
input("Thanks for playing. Press the enter key to exit.")
str.split() generates a list, so if you append it to your result you get a list of lists.
A solution would be to concatenate the 2 list (+)
You can get rid of the '\r\n' by stripping i before splitting it