Shakil-2001
Shakil-2001

Reputation: 43

Python - Calculating length of string is inaccurate for certain strings only

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

Upvotes: 4

Views: 983

Answers (5)

Cblopez
Cblopez

Reputation: 586

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!

Upvotes: 1

abhiarora
abhiarora

Reputation: 10460

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()

Upvotes: 2

MachineLearner
MachineLearner

Reputation: 977

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()

Upvotes: 1

Sven
Sven

Reputation: 1172

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!

Upvotes: 0

shahar
shahar

Reputation: 365

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.

Upvotes: 1

Related Questions