我如何修正代码,以便在输入字符时只找到单词的位置而不找到包含字符的单词?

2024-10-01 11:24:20 发布

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

sentence = input("Please enter a sentence excluding punctuation")



chars = set('0123456789!"£$%^&*()_-+={}[];:@#~/?.,<>\|`¬')
while any((c in chars) for c in sentence):
    sentence = input("Please enter another sentence excluding punctuation")
else:
    print('Your sentence is fine')
sentence = sentence.upper()

locateword = input ("Enter a word from the inputted sentence to locate")
locateword=locateword.upper()


while locateword not in sentence:

    locateword = input ("Enter another word from the inputted sentence to locate")
    locateword=locateword.upper()
else:
    print ("Your word is fine")

sentence = sentence.split()

for (position,words) in enumerate(sentence):
    if (locateword in words):
        print ("The position of your word is",position+1)

This code finds the position of an inputted word in the inputted sentence. However when a single character is the word to be located, the code finds the position of the word that contains that character, how could I fix this code so that this doesn't happen? For example, when the sentence is "I like football" and the word is "ball", the position returned is 3 as "ball" is found in "football", but I do not want this to happen.


Tags: ofthetoininputthatisposition
3条回答

试试这个:

if locateword in sentence:
    print(sentence.index(locateword)+1)

在你分开你的句子之前用这个

或者

import re
index = re.search(r'\b'+locateword+r'\b', sentence)
if index:
    print(index.start())
    print(index.end())
else:
    print("Word not in sentence")

在你再次分开你的句子之前做这个

\b表示regex中的单词边界。所以一个字也听不到

也许:

for (position,words) in enumerate(sentence):
    if (upper(locateword) == upper(words)): #case insensitive
        print ("The position of your word is",position+1)

尽管这不是你的问题,但检查字符串是否包含字母数字字符的更好方法是:

import re
sentence = input("Please enter a sentence excluding punctuation")
if re.search(r"\W", sentence):
    sentence = input("Please enter another sentence excluding punctuation")
else: print("Your sentence is ok!")

完整代码:

import re
sentence = input("Please enter a sentence excluding punctuation: ")
while( re.search(r"\W ", sentence)):
    sentence = input("Please enter another sentence excluding punctuation: ")
print("Your sentence is ok!")

sentence = sentence.split(" ")

locateword = input("Enter a word: ")
while(locateword.lower() not in [x.lower() for x in sentence]):
    locateword = input("Enter another word: ")

for (position,words) in enumerate(sentence):
    if (locateword.upper() == words.upper()): #case
        print ("The position of your word is",position+1)

在您的代码中,因为sentence已经被拆分,所以if (locateword in words)将在football中搜索ball,而不是在["I", "like", "football"]中搜索

你可以试试:

sentence = "I like to kick the ball"
words = sentence.split()
word = "ball"
if word in words:
    print words.index(word)+1
else: 
    print (word, 'is not in the inputted sentence')

相关问题 更多 >