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

2024-06-26 14:32:18 发布

您现在位置:Python中文网/ 问答频道 /正文

我正试图找出如何制作一个python程序,该程序将突出显示某个输入单词在句子中的位置,并列出该单词的位置。例如,如果句子是:“肥猫坐在垫子上” 那么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")

Tags: the程序单词satfatcat句子word
2条回答

使用^{}将句子转换为单词列表,^{}生成位置,使用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]

如果找不到单词,则结果将是空列表。

你可以使用这个代码。我是为学校的一项任务而设计的,不过如果你把它分解了会有帮助的

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...")

相关问题 更多 >