4

I'm new to programming and trying to make a basic hangman game. For some reason when calculating the length of a string from a text file some words have the length of the string calculated incorrectly. Some strings have values too high and some too low. I can't seem to figure out why. I have already ensured that there are no spaces in the text file so that the space is counted as a character.

import random

#chooses word from textfile for hangman
def choose_word():
    words = []
    with open("words.txt", "r") as file:
        words = file.readlines()

        #number of words in text file
        num_words = sum(1 for line in open("words.txt"))
        n = random.randint(1, num_words)

        #chooses the selected word from the text file
        chosen_word = (words[n-1])
        print(chosen_word)

        #calculates the length of the word
        len_word = len(chosen_word)
        print(len_word)

choose_word()
#obama returns 5
#snake, turtle, hoodie, all return 7
#intentions returns 11
#racecar returns 8
words.txt

snake
racecar
turtle
cowboy
intentions
hoodie
obama
1
  • If you do a print(words), then you will most likely find the problem. The most probable thing that is happening is that there is a newline-character at the end of the strings. Everyone, except the last one, which is the only correct one! Commented Apr 16, 2020 at 11:57

5 Answers 5

2

Use strip().

string.strip(s[, chars])

Return a copy of the string with leading and trailing characters removed. If chars is omitted or None, whitespace characters are removed. If given and not None, chars must be a string; the characters in the string will be stripped from the both ends of the string this method is called on.

Example:

>>> ' Hello'.strip()
'Hello'

Try this:

import random

#chooses word from textfile for hangman
def choose_word():
    words = []
    with open("words.txt", "r") as file:
        words = file.readlines()

        #number of words in text file
        num_words = sum(1 for line in open("words.txt"))
        n = random.randint(1, num_words)

        #chooses the selected word from the text file
        chosen_word = (words[n-1].strip())
        print(chosen_word)

        #calculates the length of the word
        len_word = len(chosen_word)
        print(len_word)

choose_word()
Sign up to request clarification or add additional context in comments.

Comments

1

You are reading a random line from a text file. Probably you have spaces in some lines after the words in those lines. For example, the word "snake" is written in the file as "snake ", so it has length of 7.

To solve it you can either:

A) Manually or by a script remove the spaces in the file

B) When you read a random line from the text, before you check the length of the word, write: chosen_word = chosen_word.replace(" ", ""). This will remove the spaces from your word.

Comments

1

You need to strip all spaces from each line. This removes the beginning and trailing spaces. Here is your corrected code.

import random

# chooses word from textfile for hangman
def choose_word():
    words = []
    with open("./words.txt", "r") as file:
        words = file.readlines()

        # number of words in text file
        num_words = sum(1 for line in open("words.txt"))
        n = random.randint(1, num_words)

        # chooses the selected word from the text file
        # Added strip() to remove spaces surrounding your words
        chosen_word = (words[n-1]).strip()
        print(chosen_word)

        # calculates the length of the word
        len_word = len(chosen_word)
        print(len_word)

choose_word()

Comments

1

Im supposing that the .txt file contains one word per line and without commas.

Maybe try to change some things here:

First, notice that the readlines() method is returning a list with all the lines but that also includes the newline string "\n".

# This deletes the newline from each line
# strip() also matches new lines as  Hampus Larsson suggested
words = [x.strip() for x in file.readlines()]

You can calculate the number of words from the length of the words list itself:

num_words = len(words)

You do not need parenthesis to get the random word

chosen_word = words[n]

It should now work correctly!

1 Comment

[x.strip() for x in file.readlines()] would do the same thing, but also match against \r\n and other whitespace-characters before or after the string.
0

in the file everyword has an \n to symbolize a new line. in order to cut that out you have to replace:

chosen_word = (words[n-1])

by

chosen_word = (words[n-1][:-1])

this will cut of the last two letters of the chosen word!

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.