如何在python中逐字符比较句子?
我想写一个代码,通过字符比较来计算给定句子中的字数,下面是我写的代码,因为我不允许使用一些奇特的实用程序,比如split(),等等,“我是python的新手,目前正在尝试通过字符比较找出如何进行字符比较,以便使用内置的utilites找出单词、行和字符串的简单计数。所以,请指导我 输入句子:我是XYZ如何在python中逐字符比较句子?,python,python-2.7,string-comparison,Python,Python 2.7,String Comparison,我想写一个代码,通过字符比较来计算给定句子中的字数,下面是我写的代码,因为我不允许使用一些奇特的实用程序,比如split(),等等,“我是python的新手,目前正在尝试通过字符比较找出如何进行字符比较,以便使用内置的utilites找出单词、行和字符串的简单计数。所以,请指导我 输入句子:我是XYZ Input_Sentence = raw_input("Enter your sentence: ") print Input_Sentence count = 0 i=0 while(Input
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循环。为什么不使用for循环呢
for char in Input_sentence:
这样你就可以重复每一个字母。
然后,您可以使用剩下的代码并检查:
if char == ' ':
如果句首或句尾有空格,以下内容将避免出现错误
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)
您可以使用try-except语法 在代码中,您使用了
while(输入句子[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
您可以自己看到输出是这样的:
...
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
它输出什么,错误是什么?[您在while状态下没有索引
Input\u-sense
-假设您的意思是Input\u-sense[i]
]谢谢,编辑了它,它能工作吗?那么您有什么问题吗?不,它给了indexer错误:字符串索引超出范围错误这会计算输入中的空格和换行数。对于一些例子,这与单词计数相同。谢谢。但是,它显示的是“我是XYZ”这个句子的单词_count=2。@user2878667这是您提供的程序逻辑的问题,而不仅仅是这个答案。当字符串不以空格结尾时会发生什么情况?@user2878667我已经更新了我的答案,以便使用您的示例。无论句末是否有换行符,都应该有效。最好不要在for循环中使用i
。它不是索引,而是一个字符。这会让新手读者感到困惑。你是对的。我只是在使用给定的代码。我对我的答案做了一些修改,希望现在更清楚。