我的代码接受了句子并在该句中找到了一个单词。
如果单词在句子中,则需要说明找到了单词以及单词所在的位置。
如果单词不在句子中,则应显示错误消息。
我有这个:
print("Please insert your sentence without punctuation")
sentence=(input())
variable1='sentence'
print("Which word would you like to find in your sentence?")
word=input()
variable2='word'
if 'word'=='COUNTRY':
'variable3'==5
'variable4'==17
if word in sentence:
print([word], "is in positions", [variable3], "and", [variable4]);
else:
print("Your word is not in the sentence!")
答案 0 :(得分:0)
Python序列提供index
方法。它为您提供元素的索引,或者如果元素不在序列中则引发错误。在字符串上,它允许您查找子字符串。
>>> 'hello world'.index('world')
6
>>> 'hello world'.index('word')
ValueError: substring not found
基本上,您必须为句子和要搜索的单词添加输入。就是这样。
print("Insert sentence without punctuation...")
sentence=input() # get input, store it to name `sentence`
print("Insert word to find...")
word=input()
try:
idx = sentence.index(word)
except ValueError: # so it wasn't in the sentence after all...
print('Word', word, 'not in sentence', repr(sentence))
else: # if we get here, IndexError was NOT thrown
print('Word', word, 'first occurs at position', idx)
这里有一些警告,例如'fooworldbar'也会匹配。正确处理这些事情取决于人们究竟想要什么。我猜你真的想要 word 职位。
如果您需要“n
单词”含义的位置,则必须将句子转换为单词列表。 str.split
这样做。然后,您可以再次使用index
。此外,如果您想要所有位置,则必须重复调用索引。
print("Insert sentence without punctuation...")
sentence = input() # get input, store it to name `sentence`
words = sentence.split() # split at whitespace, creating a list of words
print("Insert word to find...")
word=input()
positions, idx = [], -1
while idx < len(words):
try:
idx = words.index(word, idx+1)
except ValueError: # so it wasn't in the rest of the sentence after all...
break
else: # if we get here, IndexError was NOT thrown
positions.append(idx) # store the index to list of positions
# if we are here, we have searched through the whole string
if positions: # positions is not an empty list, so we have found some
print('Word', word, 'appears at positions', ', '.join(str(pos) for pos in positions))
else:
print('Word', word, 'is not in the sentence')
答案 1 :(得分:0)
我想在提供的代码中处理一些误解。
首先,
print("Please insert your sentence without punctuation")
sentence=(input())
更简单
sentence = input("Please insert your sentence without punctuation")
现在我有一个名为sentence
的变量,不应该混淆字符串'sentence'
同样我们可以说
word = input("Which word would you like to find in your sentence?")
再次给出另一个变量word
,不要混淆字符串'word'
假设我们有参数,
sentence = "Has this got an elephant in?"
我们会搜索'elephant'
发布的代码尝试使用in
,但这会发生:
>>> "elephant" in sentence
True
>>> "ele" in sentence
True
>>> "giraffe" in sentence
False
>>>
关闭。但还不够近。由于我们在'ele'
中找到了'elephant'
,所以它并不是在寻找整个单词。
如果您split
将句子翻译成单词,如其他答案所示,则可以搜索整个单词和找到位置。 (查找拆分;您可以选择除默认' '
之外的其他字符。)
words = sentence.split()
word = 'ele'
words.index(word)
如果单词不存在,您将收到错误:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: 'ele' is not in list
我会把错误处理留给你。
答案 2 :(得分:0)
您可以使用re模块:
import re
sentence = input('Sentence: ')
word = input('Word: ')
## convert word in regular expression for search method.
regex_word = r'(' + word + ')(?=\s|$)'
## initialize search var.
search = re.search(regex_word, sentence)
if search:
while search:
match_pos = search.span()
sentence = sentence[:match_pos[0]] + sentence[match_pos[1]:]
print(word + ' is in position ' + str(match_pos[0]))
search = re.search(regex_word, sentence)
else:
print(word + ' is not present in this sentence')