【问题标题】:Python - Calculating length of string is inaccurate for certain strings onlyPython - 仅对某些字符串计算字符串的长度是不准确的
【发布时间】:2020-07-29 15:37:57
【问题描述】:

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

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

【问题讨论】:

  • 如果您执行print(words),那么您很可能会发现问题。最可能发生的事情是字符串末尾有一个换行符。所有人,除了最后一位,这是唯一正确的一位!

标签: python string-length


【解决方案1】:

我假设 .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]

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

【讨论】:

  • [x.strip() for x in file.readlines()] 会做同样的事情,但也匹配 \r\n 和字符串之前或之后的其他空白字符。
【解决方案2】:

使用strip()

string.strip(s[, chars])

返回删除了前导和尾随字符的字符串副本。如果省略 chars 或 None,则删除空白字符。如果给定而不是 None,chars 必须是字符串;字符串中的字符将从调用此方法的字符串的两端剥离。

例子:

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

【讨论】:

    【解决方案3】:

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

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

    【讨论】:

      【解决方案4】:

      在文件中每个字都有一个\n 来表示一个新行。 为了消除它,您必须更换:

      chosen_word = (words[n-1])
      

      通过

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

      这将删除所选单词的最后两个字母!

      【讨论】:

        【解决方案5】:

        您正在从文本文件中读取随机行。 可能在这些行中的单词之后的某些行中有空格。 比如“snake”这个词在文件中写成“snake”,所以它的长度是7。

        要解决它,您可以:

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

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

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2021-02-09
          • 1970-01-01
          • 1970-01-01
          • 2012-01-11
          • 1970-01-01
          • 1970-01-01
          • 2012-11-07
          • 1970-01-01
          相关资源
          最近更新 更多