omz:forum

    • Register
    • Login
    • Search
    • Recent
    • Popular

    Welcome!

    This is the community forum for my apps Pythonista and Editorial.

    For individual support questions, you can also send an email. If you have a very short question or just want to say hello — I'm @olemoritz on Twitter.


    Set Error While Attempting to remove punctuation

    Pythonista
    python 3.6 python help
    3
    4
    3134
    Loading More Posts
    • Oldest to Newest
    • Newest to Oldest
    • Most Votes
    Reply
    • Reply as topic
    Log in to reply
    This topic has been deleted. Only users with topic management privileges can see it.
    • Buzzerb
      Buzzerb last edited by

      I am attempting to write a program, within which I need to load a file, and remove all punctuation from it. In attempting to do so, I receive a 'set' object does not support indexing error. I am not sure which variable is a set, and why this is failing. A simplified version of my code is below

      import string
      input_file = open("Test1.txt", "r") #Open the file 'Test1'
      input_file = input_file.read() #Convert the file to a string
      input_file = input_file.translate({None for a in string.punctuation}) #Attempt to remove punctuation. 
      #The error is thrown by the above line
      
      1 Reply Last reply Reply Quote 0
      • ccc
        ccc last edited by

        import string
        
        with open("Test1.txt", "r") as in_file:
            s = in_file.read()
        print(s)
        s = ''.join(' ' if c in string.punctuation else c for c in s)
        print(s)
        
        1 Reply Last reply Reply Quote 0
        • JonB
          JonB last edited by

          {None for ....} is a set.

          translate takes a dictionary where keys are unicode ordinals, and values are strings.

          The translate you meant to use was:

          translate({ord(x):None for x in string.punctuation})
          
          1 Reply Last reply Reply Quote 0
          • Buzzerb
            Buzzerb last edited by

            Thank you for all of the responses

            1 Reply Last reply Reply Quote 0
            • First post
              Last post
            Powered by NodeBB Forums | Contributors