当要求用户搜索某个单词时,我希望它不区分大小写。
import string
usersentence= input("Please type in a sentence without punctuation: ")
usersentence = ''.join(ch for ch in usersentence if ch not in set(string.punctuation))
print (usersentence.upper())
for i in range(1): # number of words you wont to search
word= input("Please enter a word you want to search for in the sentence: ")
words = usersentence.split(' ')
passed = False # Something to check if the word is found
for (i, words) in enumerate(words):
if (words == word):
print("your word appears in position(s): ")
print(i+1)
passed = True # The word has been found
if not passed:
print("Sorry your word does not seem to be here")
答案 0 :(得分:1)
首先不需要用单独的单词分割你的句子。你可以先检查一下:
if word.upper() in usersentence.upper():
wordlist = usersentence.upper().split('')
solution = [i for i, sentword in enumerate(wordlist) if sentword == word.upper()]
答案 1 :(得分:1)
您的问题听起来很奇怪,因为您的代码部分包含解决方案:-)!您可以使用str.upper()或str.lower()来比较没有大小写约束的字符串,就像使用str.upper()打印其中一个字符串一样。然后,您的代码应包含以这种方式转换的行:
word=input("Please enter etc.").lower() # or .upper(), as you wish
# ...
for (i, word_) in enumerate(words):
if (word_.lower() == word): # or word_.upper(), as you wish
使用str.lower()应该跟踪任何强调的char(在许多语言中都很有用)。作为法语发言人,这是我推荐的方法。但是str.upper()也应该满足你的需求。 请参阅Unicode标准的第3.13节以获取有关lower()和upper()如何处理特殊字符的信息。
答案 2 :(得分:1)
在比较字符串时使用string.lower()
使用while
循环重复代码
使用break
打破循环
while True:
sent = raw_input("Enter Sentence: ").lower() #or upper()
sent = sent.split()
word = raw_input("Enter Word to search: ").lower() #or upper()
indexes= []
for idx,ele in enumerate(sent):
if word == ele:
indexes.append(str(idx))
print ("Your word appears at indexes: "+", ".join(indexes))
response = raw_input("Do you want to continue? Y/N: ").lower()
if response == 'n':
break
else:
pass
上面的代码询问用户输入,然后检查给定句子中是否存在该单词,然后要求确认是否继续。如果用户说N
或' n'然后循环中断和程序退出。如果用户说Y
或' y'然后它又要求句子和单词。
修改:将continue
变量名替换为response