Protein
Protein

Reputation: 35

How to only get random letters and not symbols

I am trying to make a small Hangman program with unlimited trials. I think I finished building the program, but one problem is when the text includes symbols (like a period (.) for example). I tried multiple ways to only get letters out from a given file, but that didn't work.. Can anyone please help me out??

My code

fr = input("What file would you like to open: ")
f = open(fr, 'r')
text = f.read()
x = 0
textsplit = text.split()
guess_list = ''



import random
rand_letter = random.choice(textsplit)

for i in range(len(rand_letter)):
    print ('*', end = '')
print ()
while x == 0:
    guess = input("Guess a character: ")
    guess_list += guess
    if guess not in rand_letter:
        print("You're wrong bro")
    else:
        for char in rand_letter:
            if char in guess_list:
                print (char, end = ''),

            if char not in guess_list:
                print('*', end = ''),
    if guess_list == rand_letter:
        break

What I want to solve (example):enter image description here

The . in the "father." was actually pretty tough to guess, so I want to remove the symbols and only leave the alphabets.

Any help/advice/comment would be appreciated!! :)

Upvotes: 2

Views: 175

Answers (2)

M Z
M Z

Reputation: 4799

Here's one way you can do it with regex:

import re

text = "father."
text = re.sub(r"[^\w\s]", "", text)

"""
text: 'father'
"""

(This is if you want to include numbers and spaces too) If you didn't want spaces, remove the \s and if you didn't want numbers, you can remove the \w and replace it with a-zA-Z.

Here's an example without using regex

text = "father."
allowed = set("abcdefghijklmnopqrstuvwxyz ")

text = ''.join(c for c in text if c in allowed)

"""
text: 'father'
"""

Here, you can add any allowed characters to the allowed variable. I've made it a set for faster computation.

Upvotes: 1

Cyril FRANCOIS
Cyril FRANCOIS

Reputation: 88

You could try to filter the string you try to guess with this code which select only the letters in a string :

YOUR_STRING = ''.join(x for x in YOUR_STRING if x.isalpha())

With YOUR_STRING being rand_letter here.

Upvotes: 3

Related Questions