Python - 计算字符串长度仅对某些字符串不准确

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

我是编程新手,正在尝试制作基本的刽子手游戏。由于某些原因,在从文本文件计算字符串的长度时,某些单词的字符串长度计算不正确。有些字符串的值太高,有些太低。我似乎无法弄清楚为什么。我已经确保文本文件中没有 space,因此 space 被计为一个字符。

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

您正在从文本文件中随机读取一行。 可能您在这些行中的单词之后的某些行中有空格。 例如,单词"snake"在文件中写为"snake ",所以它的长度为7。

要解决它,您可以:

A) 手动或通过脚本删除文件中的空格

B) 当你从文本中随机阅读一行时,在检查单词的长度之前,写:chosen_word = chosen_word.replace(" ", "")。 这将从您的单词中删除空格。

我假设 .txt 文件每行包含一个单词且没有逗号。

也许尝试改变这里的一些东西:

首先,请注意 readlines() 方法返回一个包含所有行的列表,但也包括换行符字符串“\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()]

您可以根据 words 列表本身的长度计算单词数:

num_words = len(words)

你不需要括号来获得随机词

chosen_word = words[n]

它现在应该可以正常工作了!

文件中的每个单词都有一个\n来表示换行。 为了削减它,你必须更换:

chosen_word = (words[n-1])

来自

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

这将剪切所选单词的最后两个字母!

您需要去除每行中的所有空格。这将删除开头和结尾的空格。这是您更正后的代码。

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

使用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.

示例:

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

试试这个:

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