如何制作一个 python 程序,列出句子中某个单词的 position/positions
How to make a python program that lists the position/positions of a certain word in a sentence
我想弄清楚如何制作一个 python 程序来突出显示句子中某个输入单词的 position/positions 并列出该单词所在的位置。例如,如果句子是:"The fat cat sat on the mat"
那么 fat 这个词的位置就是 Number 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")
使用 split
to convert your sentence int a list of words, enumerate
to generate positions, and a 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...")
我想弄清楚如何制作一个 python 程序来突出显示句子中某个输入单词的 position/positions 并列出该单词所在的位置。例如,如果句子是:"The fat cat sat on the mat" 那么 fat 这个词的位置就是 Number 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")
使用 split
to convert your sentence int a list of words, enumerate
to generate positions, and a 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...")