在句子中定位特定单词

时间:2016-05-08 17:54:52

标签: python

我被要求找到输入单词出现在句子中的位置。我已经弄清楚如何使它不区分大小写,并选择要查找哪个单词,但我无法打印出单词的位置。这就是我所拥有的:

enter code here

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

2 个答案:

答案 0 :(得分:2)

要在句子中找到特定的单词位置,首先必须将句子拆分为单词,然后找到该单词的位置。

>>> sentence = 'The fat cat ate a fat mouse'
>>> words = sentence.split()
>>> words
['The', 'fat', 'cat', 'ate', 'a', 'fat', 'mouse']

现在您可以使用index查找 fat <​​/ strong>的位置。

>>> words.index('fat')
1

但是,如果你有多次出现,你已经可以看到索引没有多大帮助,因为它只输出第一次出现。

所以现在你可以做的是遍历列表并查找它是否与单词匹配。

>>> positions = [indx+1 for indx, word in enumerate(words) if word == 'fat']
>>> positions
[2, 6]

答案 1 :(得分:1)

您可以使用字符串find方法执行此操作。

如果在字符串中找不到子字符串,则返回-1,否则返回子字符串在找到时开始的索引。

如果你想要这个子字符串出现的实际生成索引(开始,结束)。你可以将单词的长度与整个跨度的起始索引结合起来。