Python Forum
Thread Rating:
  • 2 Vote(s) - 2.5 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Set Comprehension
#1
I have a text file that is going to be sent to my function. I simply need to send the words in the file back in a set. Not so difficult with a for loop. My for loop is like this:

#the text file is sent to my function. This is the only code in it.
for w in text.split():
      w.strip(punctuation)
      cypher.add(w)
print(cypher)
return cypher
The print statement is just so I can test it and make sure I did it right. This works just fine and I return the words. I need them in a set using set comprehension. I'm missing something and I'm trying to put my for loop into a comprehension, but don't know how. I've looked at multiple examples but can't figure out what I'm doing wrong. 

When I try to do it with a set comprehension, I'm doing this:
#The text file is sent to my function. Only code is below:
cypher = set()
cypher = {text.strip(punctuation()) for w in text.split()}
return cypher
Thanks for any help.
Reply
#2
I am not sure if there is something like set comprehension.
You can use list comprehension and set() it.
sypher = set([w.strip(punctuation) for w in text(split)])
"As they say in Mexico 'dosvidaniya'. That makes two vidaniyas."
https://freedns.afraid.org
Reply
#3
Just use your original set comprehension with first "text" replaced with "w" and without "()" after punctuation, as wavic posted.
cypher = {w.strip(punctuation) for w in text.split()}
String methods do not work in-place, so your original for loop did not remove punctuation at all.
Reply
#4
Thank you.
Reply


Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020