如何让这个代码告诉我单词在句子中的位置

2024-06-26 14:22:54 发布

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

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")
    for (num, x) in enumerate(sentence):
    if word == x:
        print ("Your word is in position",num,"!")

Tags: theinifonsatfatnumcat
3条回答

不需要循环,使用list.index,由try/except块保护,以防找不到字符串。list.index返回单词的第一次出现。你知道吗

sent = 'ASK NOT WHAT YOUR COUNTRY CAN DO FOR YOU ASK WHAT YOU CAN DO FOR YOUR COUNTRY.'
words = sent.split()
word = "WHAT"

try:
    print(words.index(word)+1)
except ValueError:
    print("{} is not in the sentence".format(word))

返回3,因为index在第三个位置找到了单词(数组从0开始)

您只需循环position

def word_position(word):
    for i in position:
        if word == i[1]:
            return i[0]
    return "Your word is not in the sentence"

您可以这样调用上述函数:

word = input('Which word would you like to search for?').upper()
pos = word_position(word)

输出示例:

>>> sent = 'ASK NOT WHAT YOUR COUNTRY CAN DO FOR YOU ASK WHAT YOU CAN DO FOR YOUR COUNTRY.'
>>> sen1 = sent.split()
>>> 
>>> position = enumerate(sen1)
>>> 
>>> word = input('Which word would you like to search for?').upper()
Which word would you like to search for?'what'
>>> word
'WHAT'
>>> 
>>> pos = word_position(word)
>>> print(pos)
2

尝试使用enumerate

for i in enumerate(varSplit):
    if i[1] == varWord:
        print(i[0])

您可以这样使用上面的命令:

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

varWord = input("Enter word ")

varSplit = varSentence.split()

if varWord in varSplit:
    for i in enumerate(varSplit):
        if i[1] == varWord:
            print("Your word is in position", i[0], "!")
            break  # To stop when the first position is found!
else:
    print ("Word not found")

相关问题 更多 >