如何制作一个python程序,列出句子中某个单词的位置/位置

时间:2015-12-09 19:01:00

标签: python position analysis identify

我试图弄清楚如何制作一个python程序,突出显示句子中某个输入词的位置/位置,并列出该词所在的位置。例如,如果句子是:"肥猫坐在垫子上#34; 然后,单词fat的位置将是2号。

到目前为止我得到了什么:

varSentence = ("The fat cat sat on the mat")

print (varSentence)

varWord = input("Enter word ")

varSplit = varSentence.split()

if varWord in varSplit:
    print ("Found word")
else:
    print ("Word not found")

2 个答案:

答案 0 :(得分:1)

使用split将您的句子转换为单词列表,enumerate生成位置,使用list comprehension生成结果列表。

>>> sentence = "The fat cat sat on the mat"
>>> words = sentence.lower().split()
>>> word_to_find = "the"
>>> [pos for pos, word in enumerate(words, start=1) if word == word_to_find]
[1, 6]

如果找不到该单词,您的结果将为空列表。

答案 1 :(得分:1)

您可以使用此代码。我为学校的任务创建了它,但是如果你把它分解它会有所帮助

UserSen = input("Please type in a sentence without punctuation:")
print("User has input:",UserSen)
WordFindRaw = input("Please enter a word you want to search for in the sentence:")
print("The word requested to be seacrhed for is:",WordFindRaw)
UserSenLow = UserSen.lower()
WordFind = WordFindRaw.lower()
SenLst = []
SenLst.append(UserSenLow)
print(SenLst)
if any(WordFind in s for s in SenLst):
print("Search successful. The word '",WordFind,"' has been found in position(s):")
else:
print("Search unsuccessful. The word '",WordFind,"' was not found. Please try another word...")