【问题标题】:How to compare sentence character by character in python?如何在python中逐个字符比较句子?
【发布时间】:2016-04-12 15:15:21
【问题描述】:

我想编写一个代码来通过使用字符比较来计算给定句子中的单词数,下面是我编写的代码,因为我不允许使用一些花哨的实用程序,如 split() 等。所以,可以你请指导我我在哪里犯错'我是python的新手,目前正试图弄清楚如何逐个字符进行比较,以便在不使用内置实用程序的情况下找出单词、行、字符串的简单计数。所以,请指导我。

输入句子:I am XYZ

Input_Sentence = raw_input("Enter your sentence: ")
print Input_Sentence
count = 0
i=0
while(Input_Sentence[i] != "\n"):
    if(Input_Sentence[i] == ' '):
        count=count+1
        i+=1
    else:
        i+=1
print ('Number of Words in a given sentence is :'      +str(count))

【问题讨论】:

  • 它输出什么,错误是什么? [你没有在你的 while 条件下索引Input_Sentence - 假设你的意思是Input_Sentence[i]]
  • 谢谢,已编辑
  • 而且,它有效吗?
  • 那么您遇到了什么问题?
  • 不,它给出了 IndexError: string index out of range 错误

标签: python python-2.7 string-comparison


【解决方案1】:

起初我不会在这种情况下使用 while 循环。为什么不使用 for 循环?

for char in Input_sentence:

这样你就可以遍历每一个字母。 然后您可以使用其余代码并检查:

if char == ' ':

【讨论】:

  • 最好不要在 for 循环中使用i。这不是一个索引,它是一个字符。这会让新手读者感到困惑。
  • 你是对的。我只是使用给定的代码。我已经稍微修改了我的答案,希望现在更清楚。
【解决方案2】:
# initialize the counter
word_count = 0

last_space_index = 0    

# loop through each character in the sentence (assuming Input_Sentence is a string)
for i, x in enumerate(Input_Sentence):  # enumerate to get the index of the character
    # if a space is found (or newline character for end of sentence)
    if x in (' ', '\n'):
        word_count += 1  # increment the counter
        last_space_index = i  # set the index of the last space found

if len(Input_Sentence) > (last_space_index + 1):  # check if we are at the end of the sentence (this is in case the word does not end with a newline character or a space)
    word_count += 1

# print the total number of words
print 'Number of words:', word_count

【讨论】:

  • 这会计算输入中的空格和换行符。对于某些示例,这与字数相同。
  • 谢谢。但是,它显示 word_count =2 的句子:我是 XYZ。
  • @user2878667 这是您提供的程序逻辑的问题,而不仅仅是这个答案。当字符串不以空格结尾时会发生什么?
  • @user2878667 我已经更新了我的答案以使用您的示例。无论句子末尾是否有换行符,它都应该有效。
【解决方案3】:

如果句子开头或结尾有空格,以下将避免错误。

Input_Sentence = raw_input("Enter your sentence: ")
print Input_Sentence

count = 0
sentence_length = len(Input_Sentence)
for i in range(sentence_length):
    if Input_Sentence[i] == " ":
        if i not in (0, sentence_length - 1):
            count += 1
count += 1
print "There are %s words in the sentence \"%s\"." % (count, Input_Sentence)

【讨论】:

    【解决方案4】:

    您可以使用 try-except 语法。

    在您的代码中,您使用while(Input_Sentence[i] != "\n") 来查找句子何时结束。如果您只是在i+ = 1 之前的每一步打印输出,如下所示:

    ...
    while(Input_Sentence[i] != "\n"):
       ...
            print i,Input_Sentence[i]
            i+=1
        else:
            print i,Input_Sentence[i],'*'
            i+=1
    ...
    

    你可以自己看到输出是这样的:

    Enter your sentence: Python is good     
    Python is good
    0 P *
    1 y *
    2 t *
    3 h *
    4 o *
    5 n *
    6  
    7 i *
    8 s *
    9  
    10 g *
    11 o *
    12 o *
    13 d *
    Traceback (most recent call last):
      File "prog8.py", line 19, in <module>
        while(Input_Sentence[i] != "\n"):
    IndexError: string index out of range
    

    这意味着您编写的代码在输入句子的长度内都可以正常工作。之后,当i 增加 1 并且要求代码检查Input_Sentence[i] == "\n" 是否给出IndexError。这个问题可以通过使用 Python 的异常处理工具来解决。如果是异常,则可以选择忽略 try 内的块,而是执行 except 内的块。

    Input_Sentence = raw_input("Enter your sentence: ")
    print Input_Sentence
    count = 0
    i=0
    try:
        while (Input_Sentence[i] != "\n"):
            if (Input_Sentence[i] == ' '):
                count=count+1
                i+=1
            else:
                i+=1
    except:
        count = count+1
        print ('Number of Words in a given sentence is :'      +str(count))
    

    【讨论】:

      猜你喜欢
      • 2019-01-14
      • 1970-01-01
      • 2023-03-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多